| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- namespace Day7;
- public class Hand : IComparable<Hand>
- {
- private static readonly Dictionary<Predicate<int[]>, int> Types = new Dictionary<Predicate<int[]>, int>
- {
- [counts => counts[0] == 5] = 7,
- [counts => counts[0] == 4] = 6,
- [counts => counts[0] == 3 && counts[1] == 2] = 5,
- [counts => counts[0] == 3] = 4,
- [counts => counts[0] == 2 && counts[1] == 2] = 3,
- [counts => counts[0] == 2] = 2,
- [_ => true] = 1,
- };
- private static readonly string CardOrder = "23456789TJQKA";
-
- public string Cards { get; }
- public int Type { get; }
- public int Bid { get; }
- public Hand(string cards, int bid)
- {
- Cards = cards;
- Bid = bid;
- Type = GetHandType();
- }
- private int GetHandType()
- {
- var set = new Dictionary<char, int>();
- foreach (var c in Cards)
- {
- set.TryAdd(c, 0);
- set[c]++;
- }
- var counts = set.Values.OrderDescending().ToArray();
- return Types.First(kvp => kvp.Key(counts)).Value;
- }
- public int CompareTo(Hand? other)
- {
- // this < other => negative
- var typeCmp = Type.CompareTo(other?.Type);
- if (typeCmp != 0)
- return typeCmp;
-
- for (var i = 0; i < Cards.Length; i++)
- {
- var cardCmp = CompareCard(Cards[i], other!.Cards[i]);
- if (cardCmp != 0)
- {
- return cardCmp;
- }
- }
- throw new Exception("Not expecting equal hands");
- }
- private int CompareCard(char left, char right)
- {
- var vLeft = CardOrder.IndexOf(left);
- var vRight = CardOrder.IndexOf(right);
- return vLeft.CompareTo(vRight);
- }
- }
|