Search code examples
javaswapshufflexor

Error while shuffling an Array in Java


This is what I have so far

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

So the problem seems to be when the rand value (idx) is equal to i, for the swap... it just replaces the value with 0.

How do I fix that problem?


Solution

  • Quickest fix I know; use an Integer[], Arrays.asList(T...) and Collections.shuffle(List) like

    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));
    

    Or, with your code you could add

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