November 10, 2024

Solution for Advent of Code 2017 - Day 18: Duet

Link to the puzzle text

Part 1

In this puzzle, we have a series of instructions to execute. This includes arithmetic operations, conditonal jumps and sound / receiver operations. The sound operation adds a value to an external queue, while the receive operation gets values from this queue. We should return the first value return by this receive operation.

We can implement a simple machine with all necessary registers for values, an ip register for the current position in the instruction list and a list for the sounds emitted. For the operands, we also need a function for either getting the values from a register or as an immediate value:

def get_value(registers, value):
if value in registers.keys():
value = registers[value]
else:
value = int(value)
return value

Once we get the first rcv instruction, we return the last value in the sound list.

Part 2

For part 2, we now have 2 concurrently running programs instead. The sound / receive operations now add / read values to the other programs list instead. If there is no value in the list, the programs waits. We should run both programs concurrently until both programs are waiting. The answer is the number of sounds program 1 emits until then.

We can reuse the machine implementation from part 1 and use two sets of registers for the two concurrently running machines. We execute one operations for one machine and then switch over. For the instruction execution we needed to make sure the snd operations now adds to the other list, while the rcv operation reads from its own list. We also added a counter for the number of sends and a waiting flag. This flag is set when a machine is waiting for new values in its sound queue. We can check periodically if both machines are waiting and end the execution there. 

if opcode == "rcv":
if len(register["sound"]) > 0:
sound_value = register["sound"].pop(0)
register[first_reg] = sound_value
register["wait"] = False
else:
register["wait"] = True

Link to my solutions

No comments:

Post a Comment