javaarraysrandomshuffle

Random shuffling of an array


I need to randomly shuffle the following Array:

int[] solutionArray = {1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1};

Is there any function to do that?


Solution

  • 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.*;
    
    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)
      {
        Random rnd = new Random();
        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;
        }
      }
    }