using System.Text.RegularExpressions; namespace Day15; public partial class InitializationStep { [GeneratedRegex(@"^(\w+)([=-])(\d+)?$")] private partial Regex InstructionMatcher(); private readonly string _instruction; public string Label { get; } public char Operation { get; } public int? FocalLength { get; } public InitializationStep(string instruction) { _instruction = instruction; var match = InstructionMatcher().Match(_instruction); if (!match.Success) { throw new InvalidOperationException($"Invalid instruction {_instruction}"); } Label = match.Groups[1].Value; Operation = match.Groups[2].Value[0]; FocalLength = match.Groups[3].Success ? int.Parse(match.Groups[3].Value) : null; } public void Execute(List> boxes) { var box = boxes[AsciiHash.Hash(Label)]; switch (Operation) { case '=': var index = box.FindIndex(lens => lens.Label == Label); if (index >= 0) { box[index] = new Lens(Label, FocalLength!.Value); } else { box.Add(new Lens(Label, FocalLength!.Value)); } break; case '-': box.RemoveAll(lens => lens.Label == Label); break; } } public byte GetHash() { return AsciiHash.Hash(_instruction); } }