Interview Fisher-Yates Shuffle in-place algorithm JavaScript
function shuffle(arrayToShuffle) {
var arrayLengthCountdown = arrayToShuffle.length,
lastElementVal,
randomIndex;
while (arrayLengthCountdown) {
// Pick a random element from the shortening 'length' of the array, the 'front'
randomIndex = Math.floor(Math.random() * arrayLengthCountdown--);
console.log('randomIndex: ' + randomIndex + ' arrayLengthCountdown: ' + arrayLengthCountdown + '; swapping ' + arrayToShuffle[randomIndex] + ' with ' + arrayToShuffle[arrayLengthCountdown]);
// And swap it with the last element of the shortening 'length', taken from the 'back' of the array, which gets injected into the 'front' to await getting shuffled
lastElementVal = arrayToShuffle[arrayLengthCountdown];
arrayToShuffle[arrayLengthCountdown] = arrayToShuffle[randomIndex];
arrayToShuffle[randomIndex] = lastElementVal;
console.log( arrayToShuffle );
}
return arrayToShuffle;
};
shuffle([0,1,2,3,4,5,6,7,8,9]);
This entry was posted on Wednesday, July 29th, 2015 at 9:56 am and is filed under Algorithms, Interview Questions, JavaScript. You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.