summary refs log tree commit diff
diff options
context:
space:
mode:
authordzwdz2022-12-21 21:59:50 +0100
committerdzwdz2022-12-21 21:59:50 +0100
commit497e1c54f692d2ae942372d3f21b2aecb40e8084 (patch)
tree073c6f055960a9d5faf4bc5639fefec59f0ba630
parent7eb52708df38afad7fb6e6c62d6889655b2b6ecd (diff)
day 21 part 2
-rw-r--r--22.21/part2.py40
1 files changed, 40 insertions, 0 deletions
diff --git a/22.21/part2.py b/22.21/part2.py
new file mode 100644
index 0000000..248a7fd
--- /dev/null
+++ b/22.21/part2.py
@@ -0,0 +1,40 @@
+from sys import stdin
+
+monkeys = {}
+
+for line in stdin:
+	out = line[:4]
+	parts = line[6:].split()
+	if len(parts) == 1: parts = int(parts[0])
+	monkeys[out] = parts
+
+def f(x):
+	monks = monkeys.copy()
+	monks["root"][1] = '-'
+	monks["humn"] = int(x)
+	def get(k):
+		m = monks[k]
+		if type(m) != int:
+			a = get(m[0])
+			b = get(m[2])
+			op = m[1]
+			if op == '+': m = a + b
+			if op == '-': m = a - b
+			if op == '*': m = a * b
+			if op == '/': m = a / b
+			monks[k] = m
+		return m
+	return get("root")
+
+x = 0
+# newton
+while True:
+	a = f(x)
+	print(x, a)
+	if a == 0: break
+
+	d = a - f(x-1)
+	if d == 0:
+		x += 1
+		continue
+	x = x - int(a/d)