I saw this code in Oracle documentation.
The documentation states: "The shuffle method below,unlike most naive attempts at shuffling, it's fair (all permutations occur with equal likelihood, assuming an unbiased source of randomness)".
My question is what is the purpose of variable i minus 1 within the swap method? Is - 1 really necessary for a fair randomization?
public static void shuffle(List<?> list, Random rnd) {
for (int i = list.size(); i > 1; i--)
swap(list, i - 1, rnd.nextInt(i));
}
The indexing of the array goes from 0 to its size minus 1. Because the i starts at list.size(), which is 1 more than the index of the last element, and ends at index 2, subtracting 1 from i is required. The other option is to have
public static void shuffle(List<?> list, Random rnd) {
for (int i = list.size() - 1; i > 0; i--)
swap(list, i, rnd.nextInt(i+1));
}
Examine the problem with a list of size 10 for example. If you remove the - 1
, then the first swap()
to occur will run:
swap(list, 10, rnd.nextInt(10);
As there is only 10 items in the list, and you are trying to swap item 11 (due to list indexes starting at zero), the swap will fail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With