Part 1
In this puzzle, we have a ringbuffer filled with numbers according to some special algorithm. We start with a buffer containing only 0 and the starting position set to 0. For each number, we first move the current position forward and then insert the new number after the current position. This is repeated for all numbers from 1 to 2017. We are asked to find the value after 2017 in this buffer.
We can simply recreate this algorithm according to the description:
ringbuffer = [0]
current_pos = 0
for i in range(1, 2017 + 1):
current_pos = (current_pos + num_steps) % i
ringbuffer.insert(current_pos + 1, i)
current_pos += 1
Part 2
In part 2, the filling algorithm continues until 50000000. We should return the value in the buffer immediately after the value 0.
Instead of keeping the buffer, we can keep track of the value after 0. Since the value 0 will always be in the position 0, we just need to track the current position. The value after 0 is only updated whenever the current position is 0.
current_pos = 0
value_after_0 = 0
for i in range(1, 50000000 + 1):
current_pos = (current_pos + num_steps) % i
if current_pos == 0:
value_after_0 = i
current_pos += 1
No comments:
Post a Comment