Program.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. namespace D16._1
  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> thingInLetter = new Dictionary<string, int>
  23. {
  24. { "children", 3 },
  25. { "cats", 7 },
  26. { "samoyeds", 2 },
  27. { "pomeranians", 3 },
  28. { "akitas", 0 },
  29. { "vizslas", 0 },
  30. { "goldfish", 5 },
  31. { "trees", 3 },
  32. { "cars", 2 },
  33. { "perfumes", 1 }
  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> thingInLetter, HashSet<Sue> possibleSues)
  42. {
  43. foreach (var sue in sues)
  44. {
  45. bool mayBeThatSue = true;
  46. foreach (var thing in thingInLetter)
  47. {
  48. if (sue.Things.ContainsKey(thing.Key) == false)
  49. continue;
  50. if (sue.Things[thing.Key] != thing.Value)
  51. {
  52. mayBeThatSue = false;
  53. break;
  54. }
  55. }
  56. if (mayBeThatSue) possibleSues.Add(sue);
  57. }
  58. }
  59. private static void ParseFile(string arg, List<Sue> sues)
  60. {
  61. using (var file = File.OpenText(arg))
  62. {
  63. while (true)
  64. {
  65. var line = file.ReadLine();
  66. if (line == null) break;
  67. var lr = line.Split(": ", 2);
  68. var id = int.Parse(lr[0].Substring("Sue ".Length));
  69. var sue = new Sue(id);
  70. foreach (var thing in lr[1].Split(", "))
  71. {
  72. var thinglr = thing.Split(": ");
  73. int qt = int.Parse(thinglr[1]);
  74. sue.Things.Add(thinglr[0], qt);
  75. }
  76. sues.Add(sue);
  77. }
  78. }
  79. }
  80. }
  81. }