Java - How to create an int array with random shuffled numbers in a given range

Basically, let's say I have an int array that can contain 10 numbers. This means that I can store 0-9 in each of the indices (each number only once).

If I run the code below:

int[] num = new int[10];
for(int i=0;i<10;i++){
    num[i]=i;
}

my array will look like this: [0], [1], ....., [8], [9]

But how do I randomize the assignment of a number each time I run the code? For example, I want the array to look something like this: [8], [1], [0] ..... [6], [3]

+5
source share
2 answers

Do this List<Integer>instead of an array and use the Collections.shuffle () command to shuffle it. You can build int [] from the list after shuffling.

, "Fisher-Yates Shuffle".

List:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test {
  public static void main(String args[]) {
    List<Integer> dataList = new ArrayList<Integer>();
    for (int i = 0; i < 10; i++) {
      dataList.add(i);
    }
    Collections.shuffle(dataList);
    int[] num = new int[dataList.size()];
    for (int i = 0; i < dataList.size(); i++) {
      num[i] = dataList.get(i);
    }

    for (int i = 0; i < num.length; i++) {
      System.out.println(num[i]);
    }
  }
}
+10

:

private static Random random;

/**
 * Code from method java.util.Collections.shuffle();
 */
public static void shuffle(int[] array) {
    if (random == null) random = new Random();
    int count = array.length;
    for (int i = count; i > 1; i--) {
        swap(array, i - 1, random.nextInt(i));
    }
}

private static void swap(int[] array, int i, int j) {
    int temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}
+1

All Articles