Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (2.6k points)

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?

1 Answer

0 votes
by (46k points)

Handling Collections to mix-up an array of simple types is a bit of destruction...

It is easy enough to perform 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;

    }

  }

}

Related questions

0 votes
1 answer
asked Oct 23, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Aug 29, 2019 in Java by Ritik (3.5k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...