-
Notifications
You must be signed in to change notification settings - Fork 0
/
Hand.cs
79 lines (63 loc) · 2.19 KB
/
Hand.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.Linq;
namespace PokerKata
{
public class Hand
{
public Card[] Cards { get; private set; }
public Hand(Card[] cards)
{
if (cards == null || cards.Length != 5)
throw new ArgumentException("cards");
Cards = cards;
}
public HandValue Value
{
get
{
// iteration 1: var faces = Cards.Select(c => c.Face).Distinct().Count();
var colors = Cards.Select(c => c.Suit).Distinct().Count();
var faces = Cards
.GroupBy(c => c.Rank)
.Select(g => new {Face = g.Key, Count = g.Count()})
.OrderByDescending(x => x.Count);
if (IsStraight() && colors == 1)
return HandValue.StraightFlush;
if (IsStraight())
return HandValue.Straight;
if (colors == 1)
return HandValue.Flush;
switch (faces.Count())
{
case 2:
return faces.First().Count == 4 ? HandValue.FourOfKind : HandValue.FullHouse;
case 3:
return faces.First().Count == 3 ? HandValue.ThreeOfKind : HandValue.TwoPairs;
case 4:
return HandValue.Pair;
default: // case 5:
return HandValue.HighCard;
}
}
}
private bool IsStraight()
{
var orderedCards = Cards.OrderBy(c => c.Rank).ToArray();
if (orderedCards[0].Rank == Rank.Two && orderedCards[4].Rank == Rank.Ace)
{
for (int i = 1; i < 4; i++)
{
if ((int)(orderedCards[i].Rank) != 1 + (int)(orderedCards[i - 1].Rank)) return false;
}
}
else
{
for (int i = 1; i < 5; i++)
{
if ((int)(orderedCards[i].Rank) != 1 + (int)(orderedCards[i - 1].Rank)) return false;
}
}
return true;
}
}
}