-
Notifications
You must be signed in to change notification settings - Fork 0
/
day21.py
63 lines (54 loc) · 1.97 KB
/
day21.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env python
import numpy as np
class Monkey():
def __init__(self, name, childs, operation, number):
self.name = name
self.childs = childs
self.operation = operation
self.number = number
def calculateNumber(self, monkeys):
if self.number is not None:
return self.number
monkeys[self.childs[0]].calculateNumber(monkeys)
monkeys[self.childs[1]].calculateNumber(monkeys)
self.number = self.operation(monkeys[self.childs[0]].number, monkeys[self.childs[1]].number)
return self.number
f = open("ressources/day21.txt", "r")
lines = f.readlines()
monkeys = {}
for line in lines:
instructions = line.replace("\n", "").replace(":", "").split()
monkeyName = instructions[0]
if len(instructions[1]) > 3:
childs = [instructions[1], instructions[3]]
if instructions[2] == "+":
operation = lambda x,y: x+y
if instructions[2] == "-":
operation = lambda x,y: x-y
if instructions[2] == "*":
operation = lambda x,y: x*y
if instructions[2] == "/":
operation = lambda x,y: x/y
monkey = Monkey(monkeyName, childs, operation, None)
else:
monkey = Monkey(monkeyName, None, None, float(instructions[1]))
monkeys[monkeyName] = monkey
monkeys["root"].calculateNumber(monkeys)
print("Root Monkey number is: {}".format(int(monkeys["root"].number)))
monkeys["root"].operation = lambda x,y: x-y
lowerBound = -10000000000000
upperBound = 10000000000000
while True:
mid = (lowerBound+upperBound)//2
for monkeyName in monkeys:
if monkeys[monkeyName].childs is not None:
monkeys[monkeyName].number = None
monkeys["humn"].number = mid
monkeys["root"].calculateNumber(monkeys)
if monkeys["root"].number < 0:
upperBound = mid
elif monkeys["root"].number > 0:
lowerBound = mid
else:
break
print("Human correct number is: {}".format(int(mid)))