Sean McLemon | Advent of Code

Home | Czech | Blog | GitHub | Advent Of Code | Notes


2017-12-11 - Hex Ed

(original .ipynb)
from advent import GrowableGrid

puzzle_input_str = open("puzzle_input/day11.txt").read().strip()


move = {
    "n": lambda g: g.hex_n("."),
    "nw": lambda g: g.hex_nw("."),
    "sw": lambda g: g.hex_sw("."),
    "s": lambda g: g.hex_s("."),
    "se": lambda g: g.hex_se("."),
    "ne": lambda g: g.hex_ne("."),
}


def follow_directions(input_str):
    directions = input_str.split(",")
    g = GrowableGrid("x", False)
    
    for d in directions:
        move[d](g)
        
    return g


def distance(r1, c1, r2, c2):
    steps = 0
    while (r1, c1) != (r2, c2):
        if r1 == r2:
            inc = 1 if c2 > c1 else -1
            c1 += inc
        elif c1 == c2:
            inc = 1 if r2 > r1 else -1
            r1 += inc
        elif r1 < r2 and c1 < c2:
            r1 += 1
            c1 += 1
        elif r1 > r2 and c1 > c2:
            r1 -= 1
            c1 -= 1
        steps += 1
    return steps


def part_one(input_str):
    g = follow_directions(input_str)
    return distance(g.row, g.col, g.start_row, g.start_col)


assert 3 == part_one("ne,ne,ne")
assert 0 == part_one("ne,ne,sw,sw")
assert 2 == part_one("ne,ne,s,s")
assert 3 == part_one("se,sw,se,sw,sw")


print("part one:", part_one(puzzle_input_str))
part one: 784
def part_two(input_str):
    g = follow_directions(input_str)
    distances = []
    max_rows = len(g.grid)
    
    sr, sc = g.start_row, g.start_col
    
    for r, row in enumerate(g.grid):
        # check all the first and last rows
        if r == 0 or r == max_rows - 1:
            for c, col in enumerate(row):
                if col == ".":
                    distances.append(distance(sr, sc, r, c))
        # otherwise check first or last cols
        else:
            if row[0] == ".":
                distances.append(distance(sr, sc, r, 0))
                
            elif row[-1] == ".":
                distances.append(distance(sr, sc, r, len(row)-1))
    
    return max(distances)

print("part two:", part_two(puzzle_input_str))
part two: 1558