This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET 3.5+

# Fisher-Yates-Durstenfeld Shuffle

Sometimes it is necessary to randomise the order of a sequence of values. The Fisher-Yates algorithm provides a paper-based method, which was later computerised by Richard Durstenfeld. This article implements the algorithm as a custom LINQ operator.

## Testing the Method

We can now test the Shuffle method. The code below generates fifty-two items in a sequence, each representing a playing card in a standard deck. Each playing card is represented by two characters. The first is one of A, T, J, Q, K or the digits between 2 and 9. These specify the face value of the card, with A, T, J, Q and K representing an ace, ten, jack, queen or king. The second character specifies the suit for the card. The options are D, S, H or C for diamonds, spades, hearts and clubs respectively.

Once generated, the deck is displayed in the console to show that it is ordered. Next we use the Shuffle method to randomise the pack before displaying the new order.

```static void Main(string[] args)
{
var deck = GetDeck();
ShowDeck(deck);

Console.WriteLine("\n\n^ Initial Deck ^  |  v Shuffled Deck v\n\n");

var shuffled = Shuffle(deck);
ShowDeck(shuffled);
}

private static IEnumerable<string> GetDeck()
{
var suits = "DSHC";
var values = "A23456789TJQK".Select(v => (v.ToString()));
return suits.SelectMany(s => values, (s, c) => c + s);
}

private static IEnumerable<string> Shuffle(IEnumerable<string> deck)
{
return deck.Shuffle();
}

private static void ShowDeck(IEnumerable<string> deck)
{
int count = 0;

foreach (var card in deck)
{
char suit = card[1];

if ("DH".Contains(suit))
Console.ForegroundColor = ConsoleColor.Red;
else
Console.ForegroundColor = ConsoleColor.White;

Console.Write("{0} ", card);

// 13 cards to a line
count++;
if (count == 13)
{
count = 0;
Console.WriteLine();
}
}
}```

There are 52! permutations of a deck of cards, which is approximately 8*1067 different ways in which the cards can be arranged. One possible output of the program is shown below.

```AD 2D 3D 4D 5D 6D 7D 8D 9D TD JD QD KD
AS 2S 3S 4S 5S 6S 7S 8S 9S TS JS QS KS
AH 2H 3H 4H 5H 6H 7H 8H 9H TH JH QH KH
AC 2C 3C 4C 5C 6C 7C 8C 9C TC JC QC KC

^ Initial Deck ^  |  v Shuffled Deck v

5C 4D 9C 4S 8D 2D AS 4C 5S KD 4H JC 3C
JS KC 7H TD QC QS AD 7D 8H 9H 8C 2C 2S
JH TS 3S JD TC 6H QD 8S KS 9D 9S 3H AH
5H KH TH 6D AC 7C QH 2H 6C 3D 6S 7S 5D```
2 January 2013