Part 1
In this puzzle we have a grid with cells either infected or clean. We have a cursor moving on this grid according to some rules. If the current cell is infected, we clean the cell and we turn right, otherwise we infect the cell and turn left. In both cases we move in the current direction. We should return the number newly infected cells after 10000 rounds.We again save the current position and direction as complex numbers with the real part for the columns and the imaginary part for the rows. Moving in a direction turns into addition and turning into multiplying the direction by i or -i.
cell_status = infected[cell_index(current_position)]
if cell_status == CLEAN:
current_orientation *= -1j
infected[cell_index(current_position)] = INFECTED
num_infections += 1
elif cell_status == INFECTED:
current_orientation *= 1j
infected[cell_index(current_position)] = CLEAN
current_position += current_orientation
To handle to potentially infinitly expanding grid, we used a defaultdict for the current cell status. The number of infected cells is counted in a variable.
Part 2
In part 2, there are now two more cell states. The movement rules still depend on the current state. We are should return the number of newly infected cells after 10000000 rounds.
For the new states, we can implement them in a similar manner as the previous states:
cell_status = infected[cell_index(current_position)]
if cell_status == CLEAN:
current_orientation *= 0 - 1j
infected[cell_index(current_position)] = WEAKENED
elif cell_status == WEAKENED:
num_infections += 1
infected[cell_index(current_position)] = INFECTED
elif cell_status == INFECTED:
current_orientation *= 1j
infected[cell_index(current_position)] = FLAGGED
elif cell_status == FLAGGED:
current_orientation *= -1
infected[cell_index(current_position)] = CLEAN
current_position += current_orientation
The rest of the code could stay the same, except for increasing the number of rounds.
No comments:
Post a Comment