【问题标题】:Getting the first index of a array does not move获取数组的第一个索引不动
【发布时间】:2018-11-06 14:23:45
【问题描述】:

我插入代码并解释问题:

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

【问题讨论】:

  • 什么是nextPermutationArray,你希望它做什么?
  • @Eran 对不起,我忘记放了,我更新了它
  • @BruceCollie 对不起,我更新了它

标签: java arrays random


【解决方案1】:

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

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++;
    }
}

【讨论】:

    猜你喜欢
    • 2018-06-06
    • 2023-01-23
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多