lundi 22 mai 2017

Shuffling an array, sample from which segment relative to current position?

Could you explain the reasoning for choosing r as an int between 0 and i?

    for (int i = 0; i < n; i++) {
        int r = (int) (Math.random() * (i+1));     // int between 0 and i
        int swap = a[r];
        a[r] = a[i];
        a[i] = swap;
    }

http://ift.tt/2rJJAyH

Here is a variant (from the same book):

    for (int i = 0; i < n; i++) {
        int r = i + (int) (Math.random() * (n-i)); // between i and n-1
        String temp = deck[r];
        deck[r] = deck[i];
        deck[i] = temp;
    }

http://ift.tt/2rapVej

So, why not use Math.random() * n, why use the variants? and what is the reasoning behind either?




Aucun commentaire:

Enregistrer un commentaire