In other languages there are functions to randomly mix the elements of an array (such as the PHP shuffle function ), in the case of Java I don't know if there is any similar function, so at the moment I see that functions created from code for that purpose.
Many pages ( such as the official English site ) provide function codes that can solve the problem, but some of the solutions found seem to be somewhat outdated.
Many times even the answers that circulate on the internet are not entirely effective and do not work 100% of the time.
What is sought is that the algorithm can:
- Shuffle arrays containing any type of elements (characters, numbers, strings, arrays, etc.).
- That can unorder arrays of any size.
- and that the result has an acceptable degree of entropy (disorder).
Here is a code example in java
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];
}
}
}
Code obtained from Random shuffling of an array
How can I unorder any type of array regardless of the size and type of elements it contains with a shorter code with fewer lines?
Thanks.