Naïve Shuffle Algorithm (2007)
blog.codinghorror.com·20h·
Discuss: Hacker News
Flag this post

In my previous post on shuffling, I glossed over something very important. The very first thing that came to mind for a shuffle algorithm is this:

for (int i = 0; i < cards.Length; i++)
{
int n = rand.Next(cards.Length);
Swap(ref cards[i], ref cards[n]);
}

It’s a nice, simple solution to the shuffling problem:

  1. Loop through each card in the deck.
  2. Swap the current card with another randomly chosen card.

At first blush, this seems like a perfectly reasonable way to shuffle. It’s simple, it’s straightforward, and the output looks correct. It’s the very definition of a naïve algorithm:

A naïve algorithm is a very simple solution to a problem. It is meant to describe a …

Similar Posts

Loading similar posts...