Random shuffling of an array Random shuffling of an array arrays arrays

Random shuffling of an array


Using Collections to shuffle an array of primitive types is a bit of an overkill...

It is simple enough to implement the function yourself, using for example the Fisher–Yates shuffle:

import java.util.*;import java.util.concurrent.ThreadLocalRandom;class Test{  public static void main(String args[])  {    int[] solutionArray = { 1, 2, 3, 4, 5, 6, 16, 15, 14, 13, 12, 11 };    shuffleArray(solutionArray);    for (int i = 0; i < solutionArray.length; i++)    {      System.out.print(solutionArray[i] + " ");    }    System.out.println();  }  // Implementing Fisher–Yates shuffle  static void shuffleArray(int[] ar)  {    // If running on Java 6 or older, use `new Random()` on RHS here    Random rnd = ThreadLocalRandom.current();    for (int i = ar.length - 1; i > 0; i--)    {      int index = rnd.nextInt(i + 1);      // Simple swap      int a = ar[index];      ar[index] = ar[i];      ar[i] = a;    }  }}


Here is a simple way using an ArrayList:

List<Integer> solution = new ArrayList<>();for (int i = 1; i <= 6; i++) {    solution.add(i);}Collections.shuffle(solution);


Here is a working and efficient Fisher–Yates shuffle array function:

private static void shuffleArray(int[] array){    int index;    Random random = new Random();    for (int i = array.length - 1; i > 0; i--)    {        index = random.nextInt(i + 1);        if (index != i)        {            array[index] ^= array[i];            array[i] ^= array[index];            array[index] ^= array[i];        }    }}

or

private static void shuffleArray(int[] array){    int index, temp;    Random random = new Random();    for (int i = array.length - 1; i > 0; i--)    {        index = random.nextInt(i + 1);        temp = array[index];        array[index] = array[i];        array[i] = temp;    }}