123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- #!/usr/bin/python3
- import sys
- # part 1
- def add(a, b): return a + b
- def sub(a, b): return a - b
- def mul(a, b): return a * b
- def div(a, b): return a // b
- ops = { '+': add, '-': sub, '*': mul, '/': div, }
- def part1():
- monkeys = []
- leafs = {}
- for line in sys.stdin:
- monkey = line.split()
- if len(monkey) > 2:
- name, l, op, r = monkey
- monkeys.append((name.strip(':'), l, r, op))
- else:
- name, num = monkey
- leafs[name.strip(':')] = int(num)
- print(monkeys)
- print(leafs)
- while len(monkeys) > 0:
- for i in range(len(monkeys)):
- if monkeys[i][1] in leafs and monkeys[i][2] in leafs:
- name, l, r, op = monkeys.pop(i)
- leafs[name] = ops[op](leafs[l], leafs[r])
- break
- print(monkeys)
- print(leafs)
- def part2():
- orig_monkeys = []
- orig_leafs = {}
- for line in sys.stdin:
- monkey = line.split()
- if len(monkey) > 2:
- name, l, op, r = monkey
- orig_monkeys.append((name.strip(':'), l, r, op))
- else:
- name, num = monkey
- orig_leafs[name.strip(':')] = int(num)
- print(orig_monkeys)
- print(orig_leafs)
- solved = False
- # solution found through trying out humn seeds and manual intervention
- humn = 3353687996510
- while not solved:
- monkeys = orig_monkeys.copy()
- leafs = orig_leafs.copy()
- leafs['humn'] = humn
- while len(monkeys) > 0:
- for i in range(len(monkeys)):
- if monkeys[i][1] in leafs and monkeys[i][2] in leafs:
- name, l, r, op = monkeys.pop(i)
- leafs[name] = ops[op](leafs[l], leafs[r])
- if name == 'root':
- solved = leafs[l] == leafs[r]
- print(f'root with resolution {leafs[l]} == {leafs[r]} = {solved} (humn {humn})')
- if leafs[l] < leafs[r]: return
- break
- humn += 1
- #humn += 1000
- if sys.argv[1] in '1':
- part1()
- else:
- part2()
|