When I want to shuffle an array of numbers in an array "perm" from [1...n], I wrote in Java:
int[] perm = new int[n];
for (int i = 0; i < n; i++) {
perm[i] = i;
}
for (int i = 0; i < n; i++) {
int new_place = (int) (Math.random()*n); // Exchange element with any random element.
int temp = perm[new_place];
perm[new_place] = perm[i];
perm[i] = temp;
}
But the book wrote the randomizing code as (only change is in the for loop):
for (int i = 0; i < n; i++) {
int new_place = i + (int) (Math.random() * (n-i)); // Exchange element with a random element to its right.
int temp = perm[new_place];
perm[new_place] = perm[i];
perm[i] = temp;
}
and they say that with the code they write, they ensure that the shuffle is random by choosing uniformly from the cards not yet chosen. (Contrast to my approach, where I choose from all the cards). (I believe it's the modified version of the Fisher-Yates algorithm what they wrote).
I just want to know is my code (the above one) also unbiased for random number generation or not? If yes, why? If not, why?
(The first 2 comments are for the question that I asked if what I am doing is correct for random number generation, but I wanted to ask if it is unbiased. But I didn't know this term then, sorry. For this current question, the 4th comment has a very good link to understand).