--- Day 18: Duet ---
You discover a tablet containing some strange assembly code labeled simply "Duet". Rather than bother the sound card with it, you decide to run the code yourself. Unfortunately, you don't see any documentation, so you're left to figure out what the instructions mean on your own.
It seems like the assembly is meant to operate on a set of registers that are each named with a single letter and that can each hold a single integer. You suppose each register should start with a value of 0.
There aren't that many instructions, so it shouldn't be hard to figure out what they do. Here's what you determine:
snd Xplays a sound with a frequency equal to the value ofX.set X Ysets registerXto the value ofY.add X Yincreases registerXby the value ofY.mul X Ysets registerXto the result of multiplying the value contained in registerXby the value ofY.mod X Ysets registerXto the remainder of dividing the value contained in registerXby the value ofY(that is, it setsXto the result ofXmoduloY).rcv Xrecovers the frequency of the last sound played, but only when the value ofXis not zero. (If it is zero, the command does nothing.)jgz X Yjumps with an offset of the value ofY, but only if the value ofXis greater than zero. (An offset of2skips the next instruction, an offset of-1jumps to the previous instruction, and so on.)
Many of the instructions can take either a register (a single letter) or a number. The value of a register is the integer it contains; the value of a number is that number.
After each jump instruction, the program continues with the instruction to which the jump jumped. After any other instruction, the program continues with the next instruction. Continuing (or jumping) off either end of the program terminates it.
For example:
set a 1
add a 2
mul a a
mod a 5
snd a
set a 0
rcv a
jgz a -1
set a 1
jgz a -2
- The first four instructions set
ato1, add2to it, square it, and then set it to itself modulo5, resulting in a value of4. - Then, a sound with frequency
4(the value ofa) is played. - After that,
ais set to0, causing the subsequentrcvandjgzinstructions to both be skipped (rcvbecauseais0, andjgzbecauseais not greater than0). - Finally,
ais set to1, causing the nextjgzinstruction to activate, jumping back two instructions to another jump, which jumps again to thercv, which ultimately triggers the recover operation.
At the time the recover operation is executed, the frequency of the last sound played is 4.
What is the value of the recovered frequency (the value of the most recently played sound) the first time a rcv instruction is executed with a non-zero value?