public int FixProgram(Instruction[] instructions) { ProgramResult result = new ProgramResult(); for (int i = 0; i < instructions.Length; i++) { var instruction = instructions[i]; if (instruction.Operation == Operation.nop) { instruction.Operation = Operation.jmp; result = ProcessInstructions(instructions); instruction.Operation = Operation.nop; } else if (instruction.Operation == Operation.jmp) { instruction.Operation = Operation.nop; result = ProcessInstructions(instructions); instruction.Operation = Operation.jmp; } if (result.NormalTermination == true) { return(result.Accumulator); } foreach (var reset in instructions) { reset.Visits = 0; } } throw new ArgumentException("The program couldn't be fixed"); }
public ProgramResult ProcessInstructions(Instruction[] instructions) { bool repeat = false; int index = 0; ProgramResult result = new ProgramResult { Accumulator = 0, NormalTermination = false }; try { while (!repeat) { var current = instructions[index]; if (current.Visits == 0) { switch (current.Operation) { case Operation.nop: index++; break; case Operation.acc: result.Accumulator += current.Argument; index++; break; case Operation.jmp: index += current.Argument; break; } } else { repeat = true; } current.Visits++; } } catch (Exception e) { result.NormalTermination = true; } return(result); }