获取数组的第一个索引不会移动

时间:2018-11-06 14:23:46

标签: java arrays random

我插入代码并解释问题:

public static void nextPermutationArray(int[] v) {
    int x = 0;
    int y = 0;
    Random r = new Random();

    while (x < v.length) {

        y = x + r.nextInt(v.length - x);

        int temp = v[x];
        v[x] = v[y];
        v[y] = temp;

        x++;
    }
}
public static void printArray(int[] v) {
    for (int i = 0; i < v.length; i++) {
        System.out.print(v[i]);
    }
    System.out.println("");
}

public static void main(String[] args) {

    int[] a = new int[]{0, 1, 2, 3, 4, 5, 6};
    int[] b = new int[]{0, 1, 2, 3, 4, 5, 6};

    nextPermutationArray(a);
    printArray(a);
    nextPermutationArray(a);
    printArray(a);
    nextPermutationArray(a);
    printArray(a);
    nextPermutationArray(a);
    printArray(a);

    //IntegerPermutation.permutation(a, a.length);
}

输出可以是:

  

运行:

     

1046532

     

3415620

     

3052614

     

3021564

我希望这样,例如,重要的是索引0是第一个:

  

运行:

     

0146532

     

0415623

     

0352614

     

0321564

1 个答案:

答案 0 :(得分:0)

从排列中排除数组的第一个索引很简单:

public static void nextPermutationArray(int[] v) {
    int x = 1; // changed this line
    int y = 0;
    Random r = new Random();

    while (x < v.length) {

        y = x + r.nextInt(v.length - x);

        int temp = v[x];
        v[x] = v[y];
        v[y] = temp;

        x++;
    }
}
相关问题