There is a famous problem to generate a random permutation of elements in an array - it's called shuffling. My understanding of that problem is that I have to put every element in an array into a random position. So for each element in an array I can generate a random position and put it there by swapping:
for (let i = 0; i < a.length; i++) {
const position = rand.nextInt(a.length);
const tmp = a[i];
a[i] = a[position];
a[position] = tmp;
}
This is almost what the improved Fisher–Yates shuffle algorithm is doing. However my solution is not correct. According to the link I need to generate numbers from the 0..i
range, not from 0..length
. Can anyone please explain me why it is so?
In my implementation all the numbers are still put into random positions, so what's the problem?