java - 在 Java 中改组数组时出错

标签 java swap shuffle xor

这是我目前的情况

int[] question = new int[25];

for (int i = 0; i < question.length; i++){
    question[i] = i+1;
}

Random rand = new Random();

int max = question.length-1, min = 1;

for(int i = 0; i < question.length; i++){
    int idx = rand.nextInt((max - min) + 1) + min;
    randg[i] = idx;
    question[i] ^= question[idx];
    question[idx] ^= question[i];
    question[i] ^= question[idx];

    if(question[i] == 0){
        System.out.println("Something went wrong!" + i + " " + idx);
    }
}

所以问题似乎是当 rand 值 (idx) 等于 i 时,对于交换...它只是将值替换为 0。

我该如何解决这个问题?

最佳答案

我知道的最快的修复;使用 Integer[], Arrays.asList(T...)Collections.shuffle(List)喜欢

Integer[] question = new Integer[25];
for (int i = 0; i < question.length; i++) {
    question[i] = i + 1;
}
System.out.println(Arrays.toString(question));
Collections.shuffle(Arrays.asList(question));
System.out.println(Arrays.toString(question));

或者,您可以使用您的代码添加

for(int i = 0; i < question.length; i++){
  int idx = rand.nextInt((max - min) + 1) + min;
  if (idx == i) {
    i--; 
    continue;
  }

关于java - 在 Java 中改组数组时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27236856/

相关文章:

java - 如何防止Spring AuthenticationProvider对静态或图像资源执行?

OpenGL 窗口系统屏幕撕裂预防

json - 链接 JQ if : if A then B C else D end

javascript - 随机排列 Word 中的字母。 javascript

algorithm - 如何使用 O(1) 辅助空间将数组置换为给定顺序?

java - GWT 中的正则表达式以匹配 URL

java - 如果遇到 ".setError"就停止一个 Action

java - 在 Jax-RS 中,有一种方法可以获取 header 值,而无需在每次调用中指定 @HeaderParam

tensorflow - 如何在 TensorFlow 中交换张量的 Axis ?

python - 随机选择 DataFrame 中列应切换值的行