Ejemplo n.º 1
0
class TestComputerMethods(unittest.TestCase):
    def setUp(self):
        def inc_func(arguments: List[str], registers: Dict[str, Any],
                     pc: ProgramCounter) -> ProgramCounter:
            registers[arguments[0]] += 1
            return pc + 1

        inc = Operation('inc', inc_func, [Operand.REGISTER])
        self.program = [
            Instruction(inc, ['a']),
            Instruction(inc, ['a']),
            Instruction(inc, ['b']),
            Instruction(inc, ['a']),
        ]

        self.computer = Computer(registers={'a': 0, 'b': 0})

    def test_execute_instruction(self):
        self.computer.execute_instruction(self.program[0])
        self.assertEqual(self.computer.pc, 0)
        self.assertEqual(self.computer.regs['a'], 1)

        self.computer.execute_instruction(self.program[2])
        self.assertEqual(self.computer.pc, 0)
        self.assertEqual(self.computer.regs['b'], 1)

    def test_execute(self):
        self.computer.execute(self.program)
        self.assertEqual(self.computer.pc, 4)
        self.assertEqual(self.computer.regs['a'], 3)
        self.assertEqual(self.computer.regs['b'], 1)
Ejemplo n.º 2
0
def attempt_execution(program: List[Instruction],
                      swap_instruction: int = -1) -> Tuple[int, bool]:
    comp = Computer({'acc': 0})
    executed_code = set()
    failed = False

    do_swap_instruction(program, swap_instruction)
    while 0 <= comp.pc < len(program):
        if comp.pc in executed_code:
            failed = True
            break
        else:
            executed_code.add(comp.pc)
        comp.execute_instruction(program[comp.pc])
    do_swap_instruction(program, swap_instruction)

    return comp.regs['acc'], failed