DEV Community

desgh white
desgh white

Posted on

Implementing a Fair Shuffle Algorithm for a Card Game UI

The Fisher-Yates shuffle is the standard fair shuffle. The mistake most developers make is not in the algorithm — it is in the random number generator they feed it.

Fisher-Yates, correctly

function shuffle(arr) {
  const a = [...arr];
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}
Enter fullscreen mode Exit fullscreen mode

The common bug: using Math.floor(Math.random() * a.length) instead of Math.floor(Math.random() * (i + 1)). The first produces a biased distribution — some permutations are more likely than others.

Why Math.random() is insufficient

Math.random() uses a PRNG (xorshift128+ in V8) with a 128-bit state. For a 52-card deck, there are 52! ≈ 2^226 possible permutations. A 128-bit PRNG can only produce 2^128 distinct sequences — a vanishingly small fraction. For a display-only shuffle (like a card game tutorial), this is fine. For anything involving real outcomes, use crypto.getRandomValues:

function cryptoRandom(max) {
  const arr = new Uint32Array(1);
  crypto.getRandomValues(arr);
  return arr[0] % max; // slight bias for large max, acceptable for max < 2^20
}
Enter fullscreen mode Exit fullscreen mode

Visual fairness

Even a mathematically fair shuffle can look unfair. If the same card appears in the first position three times in a row, users suspect cheating. A game interface like play at Spinhub that displays dealt hands needs to balance actual fairness with perceived fairness — sometimes that means showing the shuffle animation longer, not changing the algorithm.

Testing fairness

Run the shuffle 1M times, count how often each element lands in each position. The chi-squared test should show no significant deviation from uniform:

from scipy.stats import chisquare
observed = [count_in_position[i][j] for j in range(n)]
stat, p = chisquare(observed)
assert p > 0.01
Enter fullscreen mode Exit fullscreen mode

Takeaway

The algorithm is trivial. The randomness source and the user perception of randomness are where the real engineering lives.

Top comments (0)