Пример #1
0
        public int ComputePart2(IEnumerable <Instruction> input = null)
        {
            var instructions = (input ?? Instructions)
                               .Select(x => new { Instruction = x, State = new Day8.InstructionState() })
                               .ToArray();

            var state = new Day8.MachineState();

            var visitedInstructions = new List <int>();

            while (!instructions[state.InstructionPointer].State.Visited)
            {
                visitedInstructions.Add(state.InstructionPointer);
                var cell = instructions[state.InstructionPointer];
                state = cell.Instruction.Execute(state);
                cell.State.Visited = true;
            }

            var instructionsToSwap = visitedInstructions
                                     .Where(x => instructions[x].Instruction is Jmp || instructions[x].Instruction is Nop);

            var instructionSets = instructionsToSwap
                                  .Select(x => {
                var newSet = instructions.Select(x => x.Instruction).ToArray();

                newSet[x] = newSet[x].SwapJmpAndNop();

                return(newSet);
            });

            return(instructionSets
                   .Select(AttemptHalt)
                   .First(x => x.HasValue)
                   .Value);
        }
Пример #2
0
        private int ComputePart1()
        {
            var instructions = Instructions
                               .Select(x => new { Instruction = x, State = new Day8.InstructionState() })
                               .ToArray();

            var state = new Day8.MachineState();

            var iterations = 0;

            while (!instructions[state.InstructionPointer].State.Visited)
            {
                iterations++;
                var cell = instructions[state.InstructionPointer];
                state = cell.Instruction.Execute(state);
                cell.State.Visited = true;
            }

            return(state.Accumulator);
        }
Пример #3
0
        private int?AttemptHalt(IEnumerable <Instruction> instructions)
        {
            var cells = instructions
                        .Select(x => new { Instruction = x, State = new Day8.InstructionState() })
                        .ToArray();

            var state = new Day8.MachineState();

            while (state.InstructionPointer < cells.Length && !cells[state.InstructionPointer].State.Visited)
            {
                var cell = cells[state.InstructionPointer];
                state = cell.Instruction.Execute(state);
                cell.State.Visited = true;
            }

            if (state.InstructionPointer == cells.Count())
            {
                return(state.Accumulator);
            }

            return(null);
        }