Exemplo n.º 1
0
        public static bool ProgramHalts(InstructionProcessor processor)
        {
            var instructionExecutedTrackingArray = new bool[processor.Instructions.Length];

            instructionExecutedTrackingArray[processor.CurrentInstructionPointer] = true;

            while (!processor.Halted)
            {
                processor.Step();

                if (processor.Halted)
                {
                    continue;
                }

                if (instructionExecutedTrackingArray[processor.CurrentInstructionPointer])
                {
                    return(false);
                }

                instructionExecutedTrackingArray[processor.CurrentInstructionPointer] = true;
            }

            return(true);
        }
Exemplo n.º 2
0
        public int GetAccumulatorAfterFixingCode()
        {
            for (var i = 0; i < _instructions.Length; i++)
            {
                var instruction = _instructions[i];
                if (instruction.Operator == Operator.Jmp || instruction.Operator == Operator.Nop)
                {
                    var fixedInstructions = _instructions
                                            .Select(i => new Instruction {
                        Operator = i.Operator, Operand = i.Operand
                    })
                                            .ToArray();

                    fixedInstructions[i].Operator = instruction.Operator == Operator.Jmp ? Operator.Nop : Operator.Jmp;

                    var processor = new InstructionProcessor(fixedInstructions);

                    if (ProgramHalts(processor))
                    {
                        return(processor.Accumulator);
                    }
                }
            }

            throw new Exception("Unable to fix code");
        }
Exemplo n.º 3
0
        public int GetAccumulatorAtFirstLoop()
        {
            var instructionExecutedTrackingArray = new bool[_instructions.Length];
            var instructionProcessor             = new InstructionProcessor(_instructions);

            instructionExecutedTrackingArray[instructionProcessor.CurrentInstructionPointer] = true;

            while (!instructionProcessor.Halted)
            {
                instructionProcessor.Step();

                if (instructionExecutedTrackingArray[instructionProcessor.CurrentInstructionPointer])
                {
                    return(instructionProcessor.Accumulator);
                }

                instructionExecutedTrackingArray[instructionProcessor.CurrentInstructionPointer] = true;
            }

            return(instructionProcessor.Accumulator);
        }