Had our office Christmas lunch yesterday, with a few whiskies after so I didn't get Advent of Code finished by the end of the day!
Another machine simulation, building on Day 16's. While that allows for a more complex problem to be stated with fewer new details to outline, the problem is sufficiently different that I'm not sure how much code I'll be able to reuse.
We don't need to decipher the opcodes this time so I modelled them with an enum with attached names and execution functions.
The second part was altogether a different problem. It runs for a very very long time, so you can't get the answer just by executing it. You have to decipher the code and work out what it's doing, then compute the result without actually running it. To cut a long story short, it initialises R3 with a huge number, then uses an extremely inefficient algorithm to find numbers which are factors of that number, adding the factors up as it goes.
In analysing the code I noted that the section which computes the very large number ends with the final instruction which is a jump to the main loop. I dropped that instruction and executed the program to get the big number.
Had our office Christmas lunch yesterday, with a few whiskies after so I didn't get Advent of Code finished by the end of the day!
Another machine simulation, building on Day 16's. While that allows for a more complex problem to be stated with fewer new details to outline, the problem is sufficiently different that I'm not sure how much code I'll be able to reuse.
We don't need to decipher the opcodes this time so I modelled them with an enum with attached names and execution functions.
The program itself is then just the Instruction Pointer register binding followed by a list of instructions.
And the parser is straightforward as ever:
Executing the program is just a loop running until the IP is out of range.
And part 1 is trivial:
Part 2
The second part was altogether a different problem. It runs for a very very long time, so you can't get the answer just by executing it. You have to decipher the code and work out what it's doing, then compute the result without actually running it. To cut a long story short, it initialises R3 with a huge number, then uses an extremely inefficient algorithm to find numbers which are factors of that number, adding the factors up as it goes.
In analysing the code I noted that the section which computes the very large number ends with the final instruction which is a jump to the main loop. I dropped that instruction and executed the program to get the big number.
Then I just reimplemented the algorithm in Kotlin with a more efficient method:
Full code