Hand.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. namespace Day7;
  2. public class Hand : IComparable<Hand>
  3. {
  4. private static readonly Dictionary<Predicate<int[]>, int> Types = new Dictionary<Predicate<int[]>, int>
  5. {
  6. [counts => counts[0] == 5] = 7,
  7. [counts => counts[0] == 4] = 6,
  8. [counts => counts[0] == 3 && counts[1] == 2] = 5,
  9. [counts => counts[0] == 3] = 4,
  10. [counts => counts[0] == 2 && counts[1] == 2] = 3,
  11. [counts => counts[0] == 2] = 2,
  12. [_ => true] = 1,
  13. };
  14. private static readonly string CardOrder = "23456789TJQKA";
  15. public string Cards { get; }
  16. public int Type { get; }
  17. public int Bid { get; }
  18. public Hand(string cards, int bid)
  19. {
  20. Cards = cards;
  21. Bid = bid;
  22. Type = GetHandType();
  23. }
  24. private int GetHandType()
  25. {
  26. var set = new Dictionary<char, int>();
  27. foreach (var c in Cards)
  28. {
  29. set.TryAdd(c, 0);
  30. set[c]++;
  31. }
  32. var counts = set.Values.OrderDescending().ToArray();
  33. return Types.First(kvp => kvp.Key(counts)).Value;
  34. }
  35. public int CompareTo(Hand? other)
  36. {
  37. // this < other => negative
  38. var typeCmp = Type.CompareTo(other?.Type);
  39. if (typeCmp != 0)
  40. return typeCmp;
  41. for (var i = 0; i < Cards.Length; i++)
  42. {
  43. var cardCmp = CompareCard(Cards[i], other!.Cards[i]);
  44. if (cardCmp != 0)
  45. {
  46. return cardCmp;
  47. }
  48. }
  49. throw new Exception("Not expecting equal hands");
  50. }
  51. private int CompareCard(char left, char right)
  52. {
  53. var vLeft = CardOrder.IndexOf(left);
  54. var vRight = CardOrder.IndexOf(right);
  55. return vLeft.CompareTo(vRight);
  56. }
  57. }