Well this felt a lot easier than yesterday... Looking forward to see whether we're going to be expanding on this one in the coming days...
public record Instruction(string Operation, int Value); public class BootSequence { List<int> history = new(); public int Accumulator { get; private set; } public bool Run(Instruction[] instructions) { int i = 0; while(i < instructions.Length) { if (history.Contains(i)) { return false; } switch (instructions[i].Operation) { case "nop": history.Add(i); i++; break; case "acc": history.Add(i); Accumulator += instructions[i].Value; i++; break; case "jmp": history.Add(i); i += instructions[i].Value; break; default: break; } } return true; } }
public class Part1 : Puzzle<IEnumerable<Instruction>, int> { public override int SampleAnswer => 5; public override IEnumerable<Instruction> ParseInput(string rawInput) => rawInput .Split(Environment.NewLine) .Where(line => line.Length > 0) .Select(ParseInstruction); Instruction ParseInstruction(string line) { string op = line[..3]; int.TryParse(line[4..], out int val); return new Instruction(op, val); } public override int Solve(IEnumerable<Instruction> input) { var bootSeq = new BootSequence(); bootSeq.Run(input.ToArray()); return bootSeq.Accumulator; } }
public class Part2 : Part1 { public override int SampleAnswer => 8; public override int Solve(IEnumerable<Instruction> input) { int count = input.Count(); for (int i = 0; i < count; i++) { var aInput = input.ToArray(); var bootSeq = new BootSequence(); SwapOp(ref aInput[i]); if (bootSeq.Run(aInput)) { return bootSeq.Accumulator; }; } throw new Exception("no solution found!"); } private void SwapOp(ref Instruction instruction) { instruction = instruction with { Operation = instruction.Operation == "nop" ? "jmp" : "nop" }; } }
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Well this felt a lot easier than yesterday... Looking forward to see whether we're going to be expanding on this one in the coming days...
BootSequence
Part1
Part 2