Part 1
In this puzzle, we are operating on a hex grid. The input show a series of steps we should take in this grid and return the distance to the origin as answer.
To work effectively in hex grids, there is a guide on Redblobgames. We implemented the current position in a three axis system. We can then just iterate over the instructions, update the axis at each step by adding to one axis and subtracting one from another. We can find the position to the origin by adding the absolute values of the position and dividing by two.
for direction in directions:
if direction == "n":
pos["z"] -= 1
pos["y"] += 1
if direction == "ne":
pos["z"] -= 1
pos["x"] += 1
if direction == "nw":
pos["x"] -= 1
pos["y"] += 1
if direction == "s":
pos["y"] -= 1
pos["z"] += 1
if direction == "se":
pos["y"] -= 1
pos["x"] += 1
if direction == "sw":
pos["x"] -= 1
pos["z"] += 1
Part 1 could also be done easier by counting the number of each direction in the instructions and calculating the end position from there.
Part 2
In part 2, we should return the maximal distance to the origin during the whole series of steps.
We introduced a variable keeping track of the current maximal distance and update it after each step.
No comments:
Post a Comment