I want to shuffle an array in javascript...
I first wrote this function:
function shuffle(arr) {
for (i = 0; i < arr.length; i++) {
let temp0 = arr[Math.floor(Math.random() * arr.length)];
let temp1 = arr[Math.floor(Math.random() * arr.length)];
console.log(temp0); // select random item work correctly
console.log(temp1); // select random item work correctly
if (temp0 === temp1) { //for dont change arr[index] with save value!!!
continue;
}
temp2 = temp0;
temp0 = temp1;
temp1 = temp2;
console.log(temp0); //all temp0, temp1, temp2 are equal!!!
console.log(temp1); //all temp0, temp1, temp2 are equal!!!
console.log(temp2); //all temp0, temp1, temp2 are equal!!!
}
return arr
}
My algorithm is as follow:
- select an item randomly
- select another item randomly
- switch the two items together
But I end up with temp0, temp1 and temp2 all equal!!!
Then I changed my code to this and it works perfectly
function shuffle1(arr) {
for (i = 0; i < arr.length; i++) {
x = Math.floor(Math.random() * arr.length);
y = Math.floor(Math.random() * arr.length);
if (x === y) { //for dont change arr[index] with self !!!
continue;
}
temp0 = arr[x];
arr[x] = arr[y];
arr[y] = temp0;
}
return arr
}
The only change that has happened is that: the randomly created number for index,is assigned to a variable and then this variable is used for selecting an item in array.
Can anyone help me understand why the first example does not work as expected in the second example?
Thanks in advance