Skip to content

Commit

Permalink
Day 9 solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
nikobockerman committed Dec 9, 2023
1 parent 83e463b commit 3ba488e
Show file tree
Hide file tree
Showing 3 changed files with 251 additions and 0 deletions.
1 change: 1 addition & 0 deletions adventofcode/answers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@
6: {1: 1108800, 2: 36919753},
7: {1: 251106089, 2: 249620106},
8: {1: 16271, 2: 14265111103729},
9: {1: 1731106378, 2: 1087},
}
50 changes: 50 additions & 0 deletions adventofcode/d9.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import itertools
from typing import Iterable


def _parse_input(lines: Iterable[str]) -> Iterable[list[int]]:
for line in lines:
yield [int(x) for x in line.strip().split()]


def construct_tree_with_diffs(seq: list[int]) -> list[list[int]]:
tree: list[list[int]] = [seq]
seq_to_check = seq
while True:
diff = [b - a for a, b in itertools.pairwise(seq_to_check)]
if all(x == 0 for x in diff):
break

tree.append(diff)
seq_to_check = diff
return tree


def p1(input_str: str) -> int:
input_data = _parse_input(input_str.splitlines())

def solve(seq: list[int]) -> int:
tree = construct_tree_with_diffs(seq)

tree[-1].append(tree[-1][-1])
for i in reversed(range(len(tree) - 1)):
tree[i].append(tree[i + 1][-1] + tree[i][-1])

return tree[0][-1]

return sum(solve(seq) for seq in input_data)


def p2(input_str: str) -> int:
input_data = _parse_input(input_str.splitlines())

def solve(seq: list[int]) -> int:
tree = construct_tree_with_diffs(seq)

tree[-1].insert(0, tree[-1][0])
for i in reversed(range(len(tree) - 1)):
tree[i].insert(0, tree[i][0] - tree[i + 1][0])

return tree[0][0]

return sum(solve(seq) for seq in input_data)
Loading

0 comments on commit 3ba488e

Please sign in to comment.