-1

抱歉,如果我的问题不清楚,可以说我有int a = 1234;。如何打印如下,任意长度?

123 132 213 231 321 312

提前致谢。

4

2 回答 2

1
public class Test  {
    private static void swap(int[] p, int i, int j) {
        int t= p[i];
        p[i]= p[j];
        p[j]= t;
        return;
    }
        private static boolean nextPerm(int[] p) { // need p.length > 1
        int n= p.length;
        int i= n;
        if (i-- < 1) return false;
        for(;;) {
            int ii= i--;
            if (p[i] < p[ii]) {
                int j= n;
                while (!(p[i] < p[--j]));
                swap(p, i, j);
                for (j= n; j > ii; swap(p, --j, ii++));
                return true;
            }
            if (i == 0) {
                for (int j= n; j > i; swap(p, --j, i++));
                return false;
            }
        }
    }
    public static void main(String[] args) {
        int x = 123;
        String s = "" + x;
        int n = s.length();
        int[] p = new int[n];
        for (int i = 0; i < n; i++){
            p[i] = i;
        }
        do {
            for (int i = 0; i < n; i++){
                System.out.print(s.charAt(p[i]));
            }
            System.out.println();
        }
        while (nextPerm(p));
    }
}
于 2012-10-05T03:38:19.830 回答
-1

最后我发现,下面是代码,

class ShuffleNumber {
private static int[] a = {1,2,3};

private static void print(int[] a) {
for (int i = 0; i < a.length; i++)
    System.out.print("  " + a[i]);
    System.out.println();
}

private static void shuffle(){
int[] b = (int[])a.clone();
for (int i = b.length - 1; i > 0; i--) {
    int j = (int)Math.floor(Math.random() * (i+1));
    int temp = b[j];
    b[j] = b[i];
    b[i] = temp;
}
print(b);
}

public static void main(String[] args) {
    for (int i = 0; i < 10; i++) 
        shuffle();
}

}

于 2012-10-05T03:42:04.137 回答