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;
}
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;
}
So, why not use Math.random() * n, why use the variants? and what is the reasoning behind either?
Aucun commentaire:
Enregistrer un commentaire