Program.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. namespace D16._2
  6. {
  7. public class Sue
  8. {
  9. public int Id { get; }
  10. public Dictionary<string, int> Things = new Dictionary<string, int>();
  11. public Sue(int id) => Id = id;
  12. public override bool Equals(object obj) => obj is Sue sue && Id == sue.Id;
  13. public override int GetHashCode() => HashCode.Combine(Id);
  14. }
  15. class Program
  16. {
  17. static void Main(string[] args)
  18. {
  19. if (args.Length < 1) throw new ArgumentException();
  20. if (File.Exists(args[0]) == false) throw new FileNotFoundException();
  21. List<Sue> sues = new List<Sue>();
  22. Dictionary<string, (int, string)> thingInLetter = new Dictionary<string, (int, string)>
  23. {
  24. { "children", (3, "eq") },
  25. { "cats", (7, "gt") },
  26. { "samoyeds", (2, "eq") },
  27. { "pomeranians", (3, "lt") },
  28. { "akitas", (0, "eq") },
  29. { "vizslas", (0, "eq") },
  30. { "goldfish", (5, "lt") },
  31. { "trees", (3, "gt") },
  32. { "cars", (2, "eq") },
  33. { "perfumes", (1, "eq") }
  34. };
  35. ParseFile(args[0], sues);
  36. HashSet<Sue> possibleSues = new HashSet<Sue>();
  37. FindSue(sues, thingInLetter, possibleSues);
  38. if (possibleSues.Count > 1) throw new Exception();
  39. Console.WriteLine($"I may send my card to Aunt Sue {possibleSues.First().Id}");
  40. }
  41. private static void FindSue(List<Sue> sues, Dictionary<string, (int, string)> thingInLetter, HashSet<Sue> possibleSues)
  42. {
  43. foreach (var sue in sues)
  44. {
  45. bool mayBeThatSue = true;
  46. foreach ((string key, (int value, string op) thing) in thingInLetter)
  47. {
  48. if (sue.Things.ContainsKey(key) == false)
  49. continue;
  50. if ((thing.op == "gt" && sue.Things[key] <= thing.value) ||
  51. (thing.op == "lt" && sue.Things[key] >= thing.value) ||
  52. (thing.op == "eq" && sue.Things[key] != thing.value))
  53. {
  54. mayBeThatSue = false;
  55. break;
  56. }
  57. }
  58. if (mayBeThatSue) possibleSues.Add(sue);
  59. }
  60. }
  61. private static void ParseFile(string arg, List<Sue> sues)
  62. {
  63. using (var file = File.OpenText(arg))
  64. {
  65. while (true)
  66. {
  67. var line = file.ReadLine();
  68. if (line == null) break;
  69. var lr = line.Split(": ", 2);
  70. var id = int.Parse(lr[0].Substring("Sue ".Length));
  71. var sue = new Sue(id);
  72. foreach (var thing in lr[1].Split(", "))
  73. {
  74. var thinglr = thing.Split(": ");
  75. int qt = int.Parse(thinglr[1]);
  76. sue.Things.Add(thinglr[0], qt);
  77. }
  78. sues.Add(sue);
  79. }
  80. }
  81. }
  82. }
  83. }