Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the purpose of variable i minus 1 within the swap method? Is - 1 really necessary for a fair randomization?

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));
}
like image 393
Thor Avatar asked Feb 08 '23 04:02

Thor


2 Answers

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));
}
like image 134
indjev99 Avatar answered Feb 13 '23 22:02

indjev99


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.

like image 22
Matt Way Avatar answered Feb 14 '23 00:02

Matt Way