Reputation: 7195
A standard 52 card deck may be represented using integer values: {0,1,..,50,51}. A standard poker hand contains 5 values from this set, without repetition.
To represent all 52C5 unique hands from a deck, the following loop may be used:
for (int card1 = 0; card1 < 48; card1++)
{
for (int card2 = card1 + 1; card2 < 49; card2++)
{
for (int card3 = card2 + 1; card3 < 50; card3++)
{
for (int card4 = card3 + 1; card4 < 51; card4++)
{
for (int card5 = card4 + 1; card5 < 52; card5++)
{
var handAbcde = new List<int> { card1, card2, card3, card4, card5 };
// do something with the hand...
}
}
}
}
}
I would like to know how to make this a recursive function. I attempted but I could not preserve the ordering of the cards from lowest to highest, as it would for the for
loops above.
Example of desired output: (observe sequential ordering from lowest to highest without repetition)
0 1 2 3 4
0 1 2 3 5
0 1 2 3 6
.
.
.
47 48 49 50 49
47 48 49 50 50
47 48 49 50 51
Upvotes: 0
Views: 571
Reputation: 1712
Here's a helpful extension method, which does what you want using recursion:
public static IEnumerable<IEnumerable<T>> GetPermutations<T>(this IEnumerable<T> items, int count)
{
int i = 0;
foreach (var item in items)
{
if (count == 1) yield return new T[] { item };
else foreach (var result in items.Skip(i + 1).GetPermutations(count - 1))
yield return new T[] { item }.Concat(result);
++i;
}
}
And here's a sample use, to generate all possible combinations of five cards from a 52-card deck:
foreach (var hand in Enumerable.Range(0, 52).GetPermutations(5))
{
foreach (var card in hand)
Console.Write(card + " ");
Console.WriteLine();
}
Upvotes: 3