Sean McLemon | Advent of Code

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

2021-12-07 - The Treachery of Whales

(original .ipynb)

Day 7 puzzle input is a sequence of comma-separated integers representing positions of some crab submarines (mine is here) which can only move along one dimension. Part 1 involves finding the fewest amount of total "fuel" (expended at a rate of one fuel per step) required to move crabs to the same position. Part 2 involves doing this same calculation, but using a different calculation (one fuel expended on first step, two fuel on the second, three on the third, etc).

import math

puzzle_input_str = open("puzzle_input/day7.txt").read()
test_input_str = """16,1,2,0,4,2,7,1,2,14"""

def parse_input(input_str):
    return [int(token) for token in input_str.split(",")]

def fuel_to_align(positions, calc_fuel):
    cheapest_pos = None
    cheapest_fuel = math.inf
    for pos in range(max(positions)):
        fuel = sum(calc_fuel(p, pos) for p in positions)
        if fuel < cheapest_fuel:
            cheapest_fuel = fuel
            cheapest_pos = pos
    return cheapest_fuel    

def part_one(input_str):
    positions = parse_input(input_str)
    return fuel_to_align(positions, lambda p1,p2: abs(p1-p2))

assert 37 == part_one(test_input_str)
print("part one:", part_one(puzzle_input_str))
part one: 355150
def part_two(input_str):
    positions = parse_input(input_str)
    return fuel_to_align(positions, accum_fuel)

def accum_fuel(position, target_position):
    upper = max(position, target_position)
    lower = min(position, target_position)
    n = upper - lower
    return n + sum(range(n))
assert 168 == part_two(test_input_str)
print("part one:", part_two(puzzle_input_str))    
part one: 98368490