InitializationStep.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System.Text.RegularExpressions;
  2. namespace Day15;
  3. public partial class InitializationStep
  4. {
  5. [GeneratedRegex(@"^(\w+)([=-])(\d+)?$")]
  6. private partial Regex InstructionMatcher();
  7. private readonly string _instruction;
  8. public string Label { get; }
  9. public char Operation { get; }
  10. public int? FocalLength { get; }
  11. public InitializationStep(string instruction)
  12. {
  13. _instruction = instruction;
  14. var match = InstructionMatcher().Match(_instruction);
  15. if (!match.Success)
  16. {
  17. throw new InvalidOperationException($"Invalid instruction {_instruction}");
  18. }
  19. Label = match.Groups[1].Value;
  20. Operation = match.Groups[2].Value[0];
  21. FocalLength = match.Groups[3].Success ? int.Parse(match.Groups[3].Value) : null;
  22. }
  23. public void Execute(List<List<Lens>> boxes)
  24. {
  25. var box = boxes[AsciiHash.Hash(Label)];
  26. switch (Operation)
  27. {
  28. case '=':
  29. var index = box.FindIndex(lens => lens.Label == Label);
  30. if (index >= 0)
  31. {
  32. box[index] = new Lens(Label, FocalLength!.Value);
  33. }
  34. else
  35. {
  36. box.Add(new Lens(Label, FocalLength!.Value));
  37. }
  38. break;
  39. case '-':
  40. box.RemoveAll(lens => lens.Label == Label);
  41. break;
  42. }
  43. }
  44. public byte GetHash()
  45. {
  46. return AsciiHash.Hash(_instruction);
  47. }
  48. }