如何使用Permutation Generator Java

时间:2012-12-06 03:03:52

标签: java permutation

我已经获得了下面显示的这种置换生成器。我已将其初始化为:PermutationGenerator perm = new PermutationGenerator(4);

我试图多次使用next()函数,但我一直得到相同的结果。如何正确使用此代码生成排列?

int[] try = p.next()

for(int i=0;i<try.length;i++) {
    System.out.println(try[i]);
}

// Generator of all permutations of: 0,1,2,...,n-1

public class PermutationGenerator {
// private data

private int[] perm;
private boolean first;

// constructor

public PermutationGenerator (int n) {
    perm = new int [n];
    first = true;
}


// return the next permutation, or null if no more
// Reference: Wikipedia Permutation 5.2.2

public int[] next () {
    int n = perm.length;

    // starting permutation: 0 1 2 3 ... n-1

    if (first) {
        first = false;
        for (int i = 0 ; i < n ; i++)
            perm [i] = i;
        return perm;
    }

    // construct the next permutation
    // find largest k so that perm[k] < perm[k+1]; if none, finish

    int i, j, k, l;

    for (k = n - 2 ; k >= 0 && perm [k] >= perm [k + 1] ; k--)
        ;
    if (k < 0)
        return null; // no more

    // find largest l so that perm[k] < perm[l]

    for (l = n - 1 ; l >= 0 && perm [k] >= perm [l] ; l--)
        ;

    // swap perm[k] and perm[l]

    swap (perm, k, l);

    // reverse perm[k+1]...perm[n-1]

    for (i = k + 1, j = n - 1 ; i < j ; i++, j--)
        swap (perm, i, j);

    return perm;
}


// swap a[i] and a[j]

private static void swap (int a[], int i, int j) {
    int temp = a [i];
    a [i] = a [j];
    a [j] = temp;
}
}

1 个答案:

答案 0 :(得分:1)

import java.util.Random;

public class PermutationGenerator {

    private int[] perm;
    private static Random r = new Random();

    public PermutationGenerator(int n) {
        perm = new int[n];
        for (int i = 0; i < n; i++) {
            perm[i] = i;
        }
    }

    public int[] next() {
        helper(perm, perm.length);
        return perm;
    }

    private static void helper(int[] a, int length) {
        if (length > 1) {
            swap(a, r.nextInt(length), length - 1);
            helper(a, length - 1);
        }
    }

    private static void swap(int a[], int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    public static void main(String[] args) {
        PermutationGenerator generator = new PermutationGenerator(4);
        int[] perm = generator.next();
        for (int i = 0; i < perm.length; i++) {
            System.out.println(perm[i]);
        }
    }
}

我从午休时间开始花了五分钟时间编写了上面的工作代码。如果你愿意,试试吧。

至于你发布的代码,它不是很易读,我没有深入研究。但是我在next方法中发现的一个直接且明显的错误是它使用了perm [k] >= perm [k + 1]perm [k] >= perm [l]中的比较。

在生成排列时,在元素之间进行任何比较绝对没有必要甚至是错误的。