Menu

Why Your Card Shuffle Is Broken (and How to Fix It)
📰

Why Your Card Shuffle Is Broken (and How to Fix It)

DEV Community: javascript·Hozin·about 5 hours ago
#WLhDUTRQ
#devtojavascript#devto#dev#deck#random
Long article (391 words) — no AI summary yet.
Reading 0:00
15s threshold

The Tempting but Wrong Way

This is a shuffle method you will run into in plenty of code snippets:

deck . sort ( ( ) => Math . random ( ) - 0.5 ) ;

Enter fullscreen mode

Exit fullscreen mode

It looks elegant. It's one line. But it is not a reliable shuffle. The sort() function is built to order things, not to randomize them, and a random comparison function breaks the consistency that sorting algorithms expect. Different JavaScript engines sort differently, so the result is not guaranteed to give every ordering an equal chance. For a card game, you want that guarantee.

The Right Way: Fisher-Yates Shuffle

The Fisher-Yates shuffle (also called Knuth shuffle) gives every possible arrangement equal probability. Here's how it works:

function shuffleDeck ( ) { const suits = [ '♠' , '♥' , '♦' , '♣' ] ; const ranks = [ 'A' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '10' , 'J' , 'Q' , 'K' ] ; const deck = [ ] ;

for ( let suit of suits ) { for ( let rank of ranks ) { deck .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.