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.
To begin with, let's attack the problem of a shuffling algorithm . An algorithm that you can use that works "in-place" and has O(N) complexity is Knut's algorithm that you can check here . This is the step by step algorithm:
i
from0
toN
:j
between0
andN
i
andj
Then, regarding your question of how to shuffle any data type, you should familiarize yourself with the topic of generics in Java .
An implementation you can use that meets both requirements goes as follows:
The function
swap
swaps the numbers in the array, while the functionshuffle
loops through the elements and generates the random numbers.Parameters
<T>
allow these functions to support any type of object, to use them you add them<T>
before the return type and then use the typeT
in arguments or in the body of the function. Note however that generics don't work with primitive types likeint
orchar
, so arrays must be of types likeInteger
,String
, etc.After converting your array to a
List
You have the shuffle method of the class
Collections
which allows you to shuffle a specified list using a random default source.You can see some more examples of its use in java-shuffle-collection
https://www.programcreek.com/2012/02/java-method-to-shuffle-an-int-array-with-random-order/ you can find more detailed information.
For example, I have an app made in Java that, when it starts, randomly shows me a background image and I do it this way.
In this way, whenever I open the App, it loads a different image.