logo CodeStepByStep logo


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:

nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6

Each instruction consists of an operation (acc, jmp, or nop) and an argument (a signed number like +4 or -20).

  • acc increases or decreases a single global value called the accumulator by the value given in the argument. For example, acc +7 would increase the accumulator by 7. The accumulator starts at 0. After an 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. Then the acc +1 increases the accumulator from 0 to 1. Then 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 acc +3. It sets the accumulator to 5, and jmp -3 causes the program to continue back at the first acc +1. 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.)

Method: Write a C# method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.