diff options
author | Brian Chu <brianmchu42@gmail.com> | 2021-12-30 15:11:21 -0800 |
---|---|---|
committer | Brian Chu <brianmchu42@gmail.com> | 2021-12-30 15:11:21 -0800 |
commit | e7085453864431ace3ad8f3123b259ed0829ae74 (patch) | |
tree | 2ef1fbb0e9d02fc934b5e09d96dd187f3e371ea6 /day7.py | |
download | AdventOfCode2015-main.tar.gz |
all solutions for 2015 main
Diffstat (limited to 'day7.py')
-rw-r--r-- | day7.py | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/day7.py b/day7.py new file mode 100644 index 0000000..3c7f0c3 --- /dev/null +++ b/day7.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python + +from functools import cache +from collections import defaultdict +import operator + +ops = { + 'EQ': lambda x: x, + 'NOT': lambda x: ~x & 0xffff, + 'AND': operator.iand, + 'OR': operator.ior, + 'RSHIFT': operator.rshift, + 'LSHIFT': operator.lshift +} + +wires = defaultdict(list) +with open('day7.txt') as data: + for line in data: + calc, target = line.strip().split(' -> ') + calc = calc.split() + if len(calc) == 1: + wires[target] = ('EQ', calc[0]) + elif len(calc) == 2: + wires[target] = (calc[0], calc[1]) + else: + wires[target] = (calc[1], calc[0], calc[2]) + +@cache +def get_value(key): + try: + return int(key) + except ValueError: + pass + + op, *value = wires[key] + + if len(value) == 1: + return ops[op](get_value(value[0])) + else: + return ops[op](get_value(value[0]), get_value(value[1])) + +# part 1 +print(get_value('a')) + +# part 2 +get_value.cache_clear() + +wires['b'] = ('EQ', 3176) +print(get_value('a')) |