Fisher-Yates Shuffle in JavaScript


Posted by James Futhey on Saturday, August 02, 2014

The Fisher–Yates shuffle (named after Ronald Fisher and Frank Yates), also known as the Knuth shuffle (after Donald Knuth), is an algorithm for generating a random permutation of a finite set—in plain terms, for randomly shuffling the set. The Fisher–Yates shuffle is unbiased, so that every permutation

The Fisher–Yates shuffle (named after Ronald Fisher and Frank Yates), also known as the Knuth shuffle (after Donald Knuth), is an algorithm for generating a random permutation of a finite set—in plain terms, for randomly shuffling the set. The Fisher–Yates shuffle is unbiased, so that every permutation is equally likely. The modern version of the algorithm is also rather efficient, requiring only time proportional to the number of items being shuffled and no additional storage space.

Fisher–Yates shuffling is similar to randomly picking numbered tickets out of a hat without replacement until there are none left.

subtitle: Implementing & Visualizing CS concepts in JavaScript
cover: http://37.media.tumblr.com/abdefa4ca6ac4caf308c38b4e9ceae0f/tumblrnaj34jjHnM1st5lhmo11280.jpg
category: JavaScript
subcategory: Computer Science

When it comes down to it, what we're attempting is to take an array of elements, loop through once, and swap each element with an element in a random position.

First, we'll write a function to swap two elements in an array. This might not save us much time today, but I plan to demonstrate several other sorting methods in the future, so it should come in handy.

function swap(items, firstIndex, secondIndex){
  var temp = items[firstIndex];
  items[firstIndex] = items[secondIndex];
  items[secondIndex] = temp;
}

Next, we'll implement the Fisher-Yates Shuffle.

function shuffle(array) {
  /* Run through our array once, backwards */
  for (var a = array.length - 1; a > 0; a--) {
      /* Pick a random element */
      var b = Math.floor(Math.random() * (a + 1));
      /* Swap our current index element with our random element */
      swap(array, a, b);
  }
  return array;
}

See a visualization | ( JSBin )

//www.gravatar.com/avatar/9217f68fb557d906a5b7c625bc8bf7dd?s=250&d=mm&r=x

Tagged: Fisher-Yates Shuffle, Shuffle, Computer Science, JavaScript, Visualization

Apparition Theme
https://apparition.themespectre.com
Thoughts, stories and ideas.