How do I create an int array with randomly shuffled numbers in a given range [duplicate]

Solution 1:

Make it a List<Integer> instead of an array, and use Collections.shuffle() to shuffle it. You can build the int[] from the List after shuffling.

If you really want to do the shuffle directly, search for "Fisher-Yates Shuffle".

Here is an example of using the List technique:

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

Solution 2:

Collections class has an efficient method for shuffling:

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