Write a method named
BootCode that simulates the execution of a set of pseudo-assembly instructions and figures out the value of a global accumulator.
Your method accepts a string representing a file name as a parameter where each line contains one instruction to execute.
For example, suppose the file named
code.txt contains the following values:
Each instruction consists of an operation (
nop) and an argument (a signed number like
acc increases or decreases a single global value called the accumulator by the value given in the argument.
acc +7 would increase the accumulator by 7.
The accumulator starts at
acc instruction, the instruction immediately below it is executed next.
jmp jumps to a new instruction relative to itself.
The next instruction to execute is found using the argument as an offset from the
jmp instruction; for example,
jmp +2 would skip the next instruction,
jmp +1 would continue to the instruction immediately below it, and
jmp -20 would cause the instruction 20 lines above to be executed next.
nop stands for No Operation; it does nothing.
The instruction immediately below it is executed next.
Your code should read the given file and execute the instructions until you either reach the end of the file or until you hit a duplicate instruction.
For the code shown above, first, the
nop +0 does nothing.
acc +1 increases the accumulator from 0 to 1.
jmp +4 sets the next instruction to the other
acc +1 near the bottom.
After it increases the accumulator from 1 to 2,
jmp -4 executes, setting the next instruction to the only
It sets the accumulator to 5, and
jmp -3 causes the program to continue back at the first
This is an infinite loop: with this sequence of jumps, the program will run forever.
The moment the program tries to run any instruction a second time, you know it will never terminate and should stop executing.
So the call of
BootCode("code.txt") should return
5 since that is its last value before termination.
You may assume that the file exists and is readable,
that it follows the format described above,
and that there will be at least one instruction line in the file.
(This exercise is based on the Advent of Code 2020, day 8.)