public IntCodeComputer(long[] memory, bool outputReceiverIsSelf = false) { softwareProgram = new SoftwareProgram(memory); InstructionPointer = 0; RelativeBase = 0; _input = new Queue <long>(); _outputReceiverIsSelf = outputReceiverIsSelf; }
public void Process() { var instructionFactory = new InstructionFactory(_input); var reading = true; List <long> errorProgram = new List <long>(); do { var opCode = softwareProgram[InstructionPointer]; IInstruction instruction = instructionFactory.CreateInstruction(opCode, InstructionPointer, RelativeBase); if (instruction != null) { if (instruction is StopInstruction) { if (errorProgram.Count > 0 && errorProgram[0] != Output) { ErrorProgram = new SoftwareProgram(errorProgram.ToArray()); } reading = false; HasStopped = true; } else if (instruction is RelativeBaseOffsetInstruction) { RelativeBase = ((RelativeBaseOffsetInstruction)instruction).GetRelativeBase(ref softwareProgram); } else if (instruction is OutputInstruction) { Output = ((OutputInstruction)instruction).GetOutput(ref softwareProgram); if (OutputReceiver != null) { OutputReceiver.ReceiveInput(Output); reading = false; } else if (_outputReceiverIsSelf) { reading = false; } else { errorProgram.Add(Output); } } else { softwareProgram.ProcessInstruction(instruction); } InstructionPointer = instruction.MoveInstructionPointer(); } else { reading = false; } } while (reading && InstructionPointer < SoftwareProgram.Length); }