Part 1
In this puzzle we are given a grid and a list of instruction to walk on this grid. The instructions are either "left turn", "right turn" or "walk straight for n tiles". We are asked to find the tile after we follow the instructions.
We implement the current position as a complex number with the real part being the North-South-axis and the imaginary part the East-West-axis. So a number x + iy means a position of [x,y]. For the current orientation we also have a complex number. Rotating right and left is now simply mulitplying the orientation by either 1i or -1i, while walking for n tiles is n*orientation. For the answer we are asked to return the distance between the origin and the final tile. This is abs(tile.real) + abs(tile.imaginary).
pos = 0 + 0j
facing = 1 + 0j
for instruction in instructions:
direction, length = instruction[:1], int(instruction[1:])
if direction == "R":
facing *= 1j
else:
facing *= -1j
pos += length * facing
print(int(abs(pos.real) + abs(pos.imag)))
Part 2
For part 2, we are also asked to find the first tile visited twice.
For this, we keep a set of visited tiles and check if the current tile has been visited after each move. The move itself has to be modified from a length * facing to walking one step at a time for length steps, so we don't skip over previously visited tiles.
for i in range(length):
pos += facing
if pos in pos_visited:
print("PART 2")
print(int(abs(pos.real) + abs(pos.imag)))
pos_visited.append(pos)
No comments:
Post a Comment