102 lines
2.7 KiB
Python
102 lines
2.7 KiB
Python
import os
|
|
|
|
|
|
class Operation:
|
|
def __init__(self, operand, y: int):
|
|
self.operand: str = operand
|
|
self.y: int = y
|
|
|
|
def operate(self, input: int) -> int:
|
|
i = int(input)
|
|
j = 0
|
|
if self.y == 'old':
|
|
j = i
|
|
else:
|
|
j = int(self.y)
|
|
if (self.operand == '+'):
|
|
return i + j
|
|
if (self.operand == '*'):
|
|
return i * j
|
|
|
|
|
|
class Monkey:
|
|
def __init__(self, monkeyid: int, items, operation, testNumber: int,
|
|
actionTrue: int, actionFalse: int):
|
|
self.monkeyid = monkeyid
|
|
self.items = items
|
|
op = operation.split()
|
|
self.operation = Operation(op[1], op[2])
|
|
self.testNumber = testNumber
|
|
self.actionTrue = int(actionTrue)
|
|
self.actionFalse = int(actionFalse)
|
|
self.inspections = 0
|
|
|
|
def inspect(self, worryDivider: int, p2: bool = False):
|
|
self.inspections += 1
|
|
item: int = self.items.pop(0)
|
|
worryScore = self.operation.operate(item)//worryDivider
|
|
|
|
if (p2):
|
|
worryScore %= lcm
|
|
|
|
if worryScore % self.testNumber == 0:
|
|
return (self.actionTrue, worryScore)
|
|
else:
|
|
return (self.actionFalse, worryScore)
|
|
|
|
def __str__(self):
|
|
return "Monkey " + str(self.monkeyid) + ": "+str(self.items)+" true: " \
|
|
+ str(self.actionTrue)+" false: "+str(self.actionFalse) + \
|
|
" inspect: "+str(self.inspections)
|
|
|
|
|
|
monkeys = []
|
|
lcm = 1
|
|
|
|
|
|
def readMonkeys():
|
|
global monkeys
|
|
monkeys.clear()
|
|
|
|
input = open(os.path.dirname(__file__) +
|
|
"/input.txt", "r").read().split('\n\n')
|
|
|
|
for l in input:
|
|
data = l.splitlines()
|
|
monkeyid = data[0].split()[1][0]
|
|
items = []
|
|
itemline = data[1].strip().split(': ')
|
|
for i in itemline[1].strip().split(', '):
|
|
items.append(int(i))
|
|
operation = data[2].split('=')[1]
|
|
test = int(data[3].split()[3])
|
|
optrue = int(data[4].strip().split()[5])
|
|
opfalse = int(data[5].strip().split()[5])
|
|
monkeys.append(
|
|
Monkey(monkeyid, items, operation, test, optrue, opfalse))
|
|
global lcm
|
|
lcm = 1
|
|
for m in monkeys:
|
|
lcm = lcm*m.testNumber
|
|
|
|
|
|
def process(rounds: int, div: int, p2: bool = False):
|
|
readMonkeys()
|
|
for round in range(1, rounds+1):
|
|
for m in monkeys:
|
|
while len(m.items) != 0:
|
|
(nextmonkey, item) = m.inspect(div, p2)
|
|
monkeys[nextmonkey].items.append(item)
|
|
|
|
tot = []
|
|
|
|
for m in monkeys:
|
|
tot.append(m.inspections)
|
|
|
|
tot.sort()
|
|
return tot[-1]*tot[-2]
|
|
|
|
|
|
print("p1:", process(20, 3))
|
|
print("p2:", process(10000, 1, True))
|