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?
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?
By the way, I've noticed that this code returns a
ar.length - 1
number of elements, so if your array has 5 elements, the new shuffled array will have 4 elements. This happens because the for loop saysi>0
. If you change toi>=0
, you get all elements shuffled.The most simple solution for this Random Shuffling in 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:
You have a couple options here. A list is a bit different than an array when it comes to shuffling.
As you can see below, an array is faster than a list, and a primitive array is faster than an object array.
Sample Durations
Below, are three different implementations of a shuffle. You should only use Collections.shuffle if you are dealing with a collection. There is no need to wrap your array into a collection just to sort it. The methods below are very simple to implement.
ShuffleUtil Class
Main Method
Shuffling a Generic List
Shuffling a Generic Array
Shuffling a Primitive Array
Utility Methods
Simple utility methods to copy and convert arrays to lists and vice-versa.
Range Class
Generates a range of values, similar to Python's
range
function.Here is a solution using Apache Commons Math 3.x (for int[] arrays only):
http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/util/MathArrays.html#shuffle(int[])
Alternatively, Apache Commons Lang 3.6 introduced new shuffle methods to the
ArrayUtils
class (for objects and any primitive type).http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ArrayUtils.html#shuffle-int:A-