Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os, sys, math, functools, json, copy
- INFILE = sys.argv[1] if len(sys.argv)>1 else "input.txt"
- rawlines = []
- with open(INFILE, "r") as f:
- rawlines = f.readlines()
- lines = []
- for l in rawlines:
- lines.append(l.strip())
- print(len(lines),"lines input from",INFILE)
- #########################
- monkeys = []
- for line in lines:
- thisName = line.split(":")[0]
- thisOperation = line.split(": ")[1]
- thisMulti = " * " in thisOperation
- thisDivide = " / " in thisOperation
- thisAdd = " + " in thisOperation
- thisSubtract = " - " in thisOperation
- thisVal = None
- thisTarget1 = False
- thisTarget2 = False
- if not thisMulti and not thisDivide and not thisAdd and not thisSubtract:
- thisVal = int(thisOperation)
- else:
- thisTarget1 = thisOperation.split(" ")[0]
- thisTarget2 = thisOperation.split(" ")[2]
- monkey = {
- "name": thisName,
- "value": thisVal,
- "multiply": thisMulti,
- "divide": thisDivide,
- "add": thisAdd,
- "subtract": thisSubtract,
- "target1": thisTarget1,
- "target2": thisTarget2
- }
- monkeys.append(monkey)
- def getMonkeyIdx(monkeyname) -> int:
- for x in range(len(monkeys)):
- if monkeys[x]["name"] == monkeyname:
- return x
- assert False
- def getMonkeyVal(monkeyname):
- monkeyIdx = getMonkeyIdx(monkeyname)
- M = monkeys[monkeyIdx]
- if M["value"] is not None:
- return M["value"]
- if M["multiply"]:
- return getMonkeyVal(M["target1"]) * getMonkeyVal(M["target2"])
- if M["divide"]:
- return getMonkeyVal(M["target1"]) / getMonkeyVal(M["target2"])
- if M["add"]:
- return getMonkeyVal(M["target1"]) + getMonkeyVal(M["target2"])
- if M["subtract"]:
- return getMonkeyVal(M["target1"]) - getMonkeyVal(M["target2"])
- print("part 1:", int(getMonkeyVal("root"))) # 54703080378102
- humanMonkeyIdx = getMonkeyIdx("humn")
- rootTarget1 = monkeys[getMonkeyIdx("root")]["target1"]
- rootTarget2 = monkeys[getMonkeyIdx("root")]["target2"]
- x = 0
- while True:
- monkeys[humanMonkeyIdx]["value"] = x
- diff = abs(getMonkeyVal(rootTarget1) - getMonkeyVal(rootTarget2))
- #print(x, "=", diff)
- if diff == 0:
- print("part 2:", x)
- sys.exit(1)
- else:
- x += max(int(diff*0.1), 1) # this is sketchy (going past 0.1 causes negative)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement