Collections.shuffle()
goes through each index of a Collection
backwards and then swaps it with a random index including or before it. I was wondering why, so I tried doing the same thing but swapping with any random index in the Collection
.
Here is the shuffling part of the Collections.shuffle() code:
for (int i=size; i>1; i--)
swap(arr, i-1, rnd.nextInt(i));
And here is my algorithm:
Random r = new Random();
for (int i = 0; i < a.size(); i++) {
int index = r.nextInt(a.size());
int temp = a.get(i);
a.set(i, a.get(index));
a.set(index, temp);
}
I found that Collections.shuffle()
was much more evenly distributed than my code when I ran both on the same ArrayList
one million times. Also, when running my code on:
[0, 1, 2, 3, 4]
it seems that the following permutations consistently occur most frequently:
[1, 0, 3, 4, 2]
[1, 2, 3, 4, 0]
[1, 2, 0, 4, 3]
[0, 2, 3, 4, 1]
[1, 2, 3, 0, 4]
Could someone please explain why?