diff options
author | Brian Chu <brianmchu42@gmail.com> | 2021-12-19 22:57:37 -0800 |
---|---|---|
committer | Brian Chu <brianmchu42@gmail.com> | 2021-12-19 22:57:37 -0800 |
commit | d4f482804b9777768fa4f9fedde0cd549578502b (patch) | |
tree | 211098ceaad6046234e0f55fe86dc539f791d4a4 /day18.py | |
parent | 04d85bf194d50f8da584a8c657d7490649befb7c (diff) | |
download | AdventOfCode2021-d4f482804b9777768fa4f9fedde0cd549578502b.tar.gz |
catch up on solutions up to day 20
Diffstat (limited to 'day18.py')
-rw-r--r-- | day18.py | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/day18.py b/day18.py new file mode 100644 index 0000000..7711309 --- /dev/null +++ b/day18.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python + +def unpack(line, n=1): + '''flattens the number while also keeping track of level''' + if line == []: + return line + if isinstance(line[0], list): + return unpack(line[0], n+1) + unpack(line[1:], n) + return [[line[0], n]] + unpack(line[1:], n) + +with open('day18.txt') as data: + nums = [] + for line in data: + num = unpack(eval(line)) + nums.append(num) + +def explode(line): + for i in range(len(line)-1): + num1, level1 = line[i] + num2, level2 = line[i+1] + if level1 == level2 == 5: + line[i] = [0, 4] + if i != 0: + line[i-1][0] += num1 + if i+2 != len(line): + line[i+2][0] += num2 + line.pop(i+1) + return True + return False + +def split(line): + for i in range(len(line)): + num, level = line[i] + if num >= 10: + line[i:i+1] = [num//2, level+1], [num//2 + num%2, level+1] + return True + return False + +def reduce_num(line): + while True: + if explode(line): + continue + if not split(line): + break + + return line + +def magnitude(num): + while len(num) > 1: + for i, ((num1, depth1), (num2, depth2)) in enumerate(zip(num, num[1:])): + if depth1 != depth2: continue + val = num1 * 3 + num2 * 2 + num = num[:i] + [[val, depth1-1]] + num[i+2:] + break + return num[0][0] + +# part 1 +curr = nums[0] +for line in nums[1:]: + summation = list(map(lambda x: [x[0], x[1] + 1], curr + line)) + curr = reduce_num(summation) +print(magnitude(curr)) + +# part 2 +from itertools import permutations +permute_nums = permutations(nums, 2) +maximum = 0 +for perm in permute_nums: + summation = reduce_num(list(map(lambda x: [x[0], x[1]+1], perm[0] + perm[1]))) + maximum = max(maximum, magnitude(summation)) +print(maximum) |