JS — Shuffle Cards (Or Any Elements) With the Fisher-Yates Shuffle Algorithm

JC jawe.sol
2 min readFeb 8, 2017

--

In this Quick Tip, I will show you how to implement the Fisher-Yates shuffle algorithm. Once we have learned how it works, we will use it to shuffle a virtual deck of cards.

Note: Although this tutorial is written using JavaScript, you should be able to use the same techniques and concepts in almost any game development environment.

In this Quick Tip, I will show you how to implement the Fisher-Yates shuffle algorithm. Once we have learned how it works, we will use it to shuffle a virtual deck of cards.

Note: Although this tutorial is written using JavaScript, you should be able to use the same techniques and concepts in almost any game development environment.

1. Introduction to the Algorithm

There are several ways to shuffle a set of elements, as demonstrated in this post. While those are all valid options, the one method I have always used is the one implemented by the Fisher-Yates Shuffle Algorithm.

I like this method because it does an “in place” shuffle without the need to create a new array (or whatever data structure you happen to be using).

2. Using the Algorithm

If you gave the Wikipedia page a quick read through, you’ll have seen it mentions a couple of different methods of implementing the algorithm. The one we will be using is called the “Modern Method”:

To shuffle an array a of n elements (indices 0...n-1):
for i from (n − 1) down to 1 do
set j to a random integer with 0 ≤ j ≤ i
exchange a[j] and a[i]
  1. You start with the last element in the list (the top card in the deck, if you like).
  2. You pick another element at random between the first one and your selected one.
  3. You swap these two elements.
  4. You pick the last-but-one element in the list (the second card in the deck), and repeat #1-#3 until you reach the bottom of the deck.

--

--