#!/usr/bin/env python # 2022 - Advent Of Code 11 part 1 # Monkey 0: # Starting items: 79, 98 # Operation: new = old * 19 # Test: divisible by 23 # If true: throw to monkey 2 # If false: throw to monkey 3 class Monkey: # pylint: disable=too-many-arguments def __init__(self, sitems, op, op2, divisible, ta, tf): self.items = sitems self.operation = op self.operand = op2 self.divisible = divisible self.action_true = ta self.action_false = tf self.activity = 0 def print(self): print(f'items: {self.items}') print(f'operation: {self.operation} {self.operand}') print(f'divisible: {self.divisible}') print(f'true: {self.action_true}') print(f'false: {self.action_false}') # print(f'{}') print() def operate(self, w): if self.operation == '+': return w + self.operand if self.operation == '*': if self.operand == 'old': return w * w return w * self.operand def turn(self, other_monkeys): for item in self.items: self.activity += 1 w = item w = self.operate(w) w = int(w / 3) # round if w % self.divisible == 0: # print(f'throwing worry level {w} to monkey {self.action_true}') other_monkeys[self.action_true].throw_item(w) else: # print(f'throwing worry level {w} to monkey {self.action_false}') other_monkeys[self.action_false].throw_item(w) self.items = [] def throw_item(self, item): self.items.append(item) def parse_file(file): m_list = [] with open(file, encoding="utf-8") as f: line = f.readline() # monkey while line: line = f.readline().strip() item_list = line.split('Starting items:')[1] items = [int(i) for i in item_list.split(',')] # print(items) line = f.readline().strip() oper = line.split('Operation: new = old ')[1] operation = oper[0] # print(oper) if oper[1:] == ' old': operand = 'old' else: operand = int(oper[1:]) line = f.readline().strip() nb_div = int(line.split('Test: divisible by ')[1]) line = f.readline().strip() v_true = int(line.split('If true: throw to monkey ')[1]) line = f.readline().strip() v_false = int(line.split('If false: throw to monkey ')[1]) line = f.readline().strip() # empty line m_list.append(Monkey(items, operation, operand, nb_div, v_true, v_false)) line = f.readline() # monkey return m_list # inputfile = 'input_example.txt' inputfile = 'input.txt' monkeys = [] monkeys = parse_file(inputfile) # for n, m in enumerate(monkeys): # print(f'monkey {n}') # m.print() nb_round = 20 for r in range(0, nb_round): print(f'round {r+1}') for n, m in enumerate(monkeys): # print(f'monkey {n}') m.turn(monkeys) for n, m in enumerate(monkeys): print(f'monkey {n} items: {m.items}') # find 2 max active_list = [m.activity for m in monkeys] active_dict = {v: k for k, v in enumerate(active_list)} # print(active_dict) print(sorted(active_dict)[-2:]) two_max = sorted(active_dict)[-2:] print(two_max[0] * two_max[1])