Skip to content

Instantly share code, notes, and snippets.

@dannas
Created December 2, 2021 15:11
Show Gist options
  • Save dannas/1412fc959d81595a31095ee30456850f to your computer and use it in GitHub Desktop.
Save dannas/1412fc959d81595a31095ee30456850f to your computer and use it in GitHub Desktop.
Solutions to AoC 2021
import re
from itertools import permutations, combinations, count, chain, product
from typing import Dict, Tuple, Set, List, Iterator, Optional, Union
from collections import defaultdict
from functools import lru_cache
from math import prod
#### FILE INPUT AND PARSING ######################################
# Adapted from Peter Norvigs Advent of Code solutions, https://github.com/norvig/pytudes.
def Input(day, parser=str.split, sep='\n') -> list:
"For this day's input file, return a list of sections separated by |sep| ad parsed by |parser|."
if isinstance(day, int):
sections = open(f'advent2021/input{day}.txt').read().rstrip('\n').split(sep)
return [parser(section) for section in sections]
return [parser(section) for section in day.rstrip('\n').split(sep)]
def do(day, *answers) -> List[int]:
"E.g., do(3) returns [day3_1(in3), day3_2(in3)]. Verifies `answers` if given."
g = globals()
got = []
for part in (1, 2):
fname = f'day{day}_{part}'
if fname in g:
got.append(g[fname](g[f'in{day}']))
if len(answers) >= part:
assert got[-1] == answers[part - 1], (
f'{fname}(in{day}) got {got[-1]}; expected {answers[part - 1]}')
return got
#################################################################
# Day 1: Sonar Sweep
# 1. Count number of numbers larger than the previous
# 2. Count number of sum of windows larger than previous sums
in1 : List[int] = Input(1, int)
def day1_1(nums):
return sum(1 for x, y in zip(nums, nums[1:]) if y > x)
def day1_2(nums):
sums = [sum(win) for win in zip(nums, nums[1:], nums[2:])]
return sum(1 for x, y in zip(sums, sums[1:]) if y > x)
do(1, 1754, 1789)
# Day 2: Dive!
# 1. Calculate position from movement instructions
# 2. Use aim when calculating the position
Instruction = Tuple[str, int]
def parse_instr(line) -> Instruction:
dir, val = line.split(' ')
return dir, int(val)
in2 : List[Instruction] = Input(2, parse_instr)
def day2_1(instructions):
pos, depth = 0, 0
for dir, val in instructions:
if dir == 'forward':
pos += val
elif dir == 'down':
depth += val
elif dir == 'up':
depth -= val
return pos * depth
def day2_2(instructions):
pos, depth, aim = 0, 0, 0
for dir, val in instructions:
if dir == 'forward':
pos += val
depth += aim * val
elif dir == 'down':
aim += val
elif dir == 'up':
aim -= val
return pos * depth
do(2, 1524750,1592426537)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment