java程序以整数打印数字为shuffle

时间:2012-10-05 03:26:17

标签: java int shuffle

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

123 132 213 231 321 312

提前致谢。

2 个答案:

答案 0 :(得分: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));
    }
}

答案 1 :(得分:-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();
}

}