Flip cards and match pairs. A classic memory-training game with best-score tracking.
When this game starts, it takes a list of pairs (e.g., [Apple, Apple, Banana, Banana]) and shuffles them so they are distributed randomly across the grid.
A beginner programmer might try to shuffle an array by using the built-in sorting function: array.sort(() => Math.random() - 0.5).
This is considered a terrible practice. Sorting algorithms are designed for transitive logic (if A > B and B > C, then A > C). When you introduce randomness into a sort function, the browser's engine gets confused, resulting in an uneven distribution where some cards are statistically much more likely to stay near their original positions.
The standard computer science algorithm for shuffling an array is the Fisher-Yates Shuffle (specifically the Durstenfeld version):
Because the Fisher-Yates shuffle only touches each card exactly once, its time complexity is O(N). This guarantees a perfectly uniform mathematical distribution while remaining incredibly fast, even for decks with millions of cards.
Why is array.sort(() => Math.random() - 0.5) a bad way to shuffle an array?