Hy guys. I am making a game of Memory and to achieve that I had to somehow shuffle images in Array. I found an old answer on Stack Overflow, Fisher–Yates shuffle, and used that, and it works but I don't understand how. Can someone explain step by step and what each element represents in this code. Especially first line, how are there three values in a variable. Thank you.
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
Used like so:
var arr = [2, 11, 37, 42];
arr = shuffle(arr);
console.log(arr);