Sean McLemon | Advent of Code

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


2021-12-02 - Dive!

(original .ipynb)

Day 2 puzzle input is a sequence of commands (forward n, up n or down n) which manipulate a submarine's position (mine is here). Part 1 involves interpreting these as directly adjusting the submarine's horizontal and depth - the answer being the product of these. Part 2 is the same but with up n/down n interpreted as adjusting a parameter aim and each forward movement both adjusting the current horizontal position (by n) and the current depth (by n * aim). The answer was still the product of horizontal and depth.

puzzle_input_str = open("puzzle_input/day2.txt").read()

test_input_str = """forward 5
down 5
forward 8
up 3
down 8
forward 2"""


def parse_line(line):
    if line.startswith("forward"):
        return (int(line.removeprefix("forward ")), 0)
    
    if line.startswith("up"):
        return (0, -int(line.removeprefix("up ")))
    
    if line.startswith("down"):
        return (0, int(line.removeprefix("down ")))
    
    return line

def parse_input_lines(input_str):
    return [parse_line(line) for line in input_str.split("\n")]

def part_one(input_str):
    commands = parse_input_lines(input_str)
    horizontal, depth = (0, 0)
    for dh, dd in commands:
        horizontal += dh
        depth += dd
    
    return horizontal * depth

assert 150 == part_one(test_input_str)
print("part one:", part_one(puzzle_input_str))
part one: 1580000
def part_two(input_str):
    commands = parse_input_lines(input_str)
    horizontal, aim, depth = (0, 0, 0)
    for dh, da in commands:
        horizontal += dh
        aim += da
        depth += dh * aim
    
    return horizontal * depth

assert 900 == part_two(test_input_str)
print("part two:", part_two(puzzle_input_str))
part two: 1251263225