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]);

Leave a Reply

You must be logged in to post a comment.