Skip to content
advent of code 2017

day 11

hex ed

approach

the hex grid uses "odd-q" offset coordinates (following red blob games' hexagon guide, linked in a comment). each direction is a match case whose row change depends on whether the current column is odd.

to measure distance, both points are converted to axial coordinates, where hex distance has a closed form. part 1 is the distance of the final position from the origin; part 2 tracks the maximum distance seen along the way. a commented-out bfs in the file shows the earlier, slower way of computing distance.

the trick

convert offset coordinates to axial, and hex distance becomes half the sum of three absolute differences.

python
def oddq_to_axial(row, col):
    q = col
    r = row - (col - (col&1)) // 2
    return q, r

def axial_subtract(ar, ac, br, bc):
    return ar - br, ac - bc

def axial_distance(ar, ac, br, bc):
    vecr, vecc = axial_subtract(ar, ac, br, bc)
    return (abs(vecr) + abs(vecr + vecc) + abs(vecc)) // 2