Day 11 - Advent of Code 2022
Working solutions for the day 11 puzzles.
Part One
""" day_11_01.py """
# usage: python3 day_11_01.py < input
import sys
monkeys = []
barrel = {}
active = None
for line in sys.stdin:
text = line.split()
if not text:
continue
if text[0] == 'Monkey':
active = text[1].removesuffix(':')
monkeys.append(active)
elif text[0] == 'Starting':
barrel[(active, 'items')] = list(map(int,
''.join(text[2:]).split(',')))
elif text[0] == 'Operation:':
if text[-1] == 'old':
text[-1] = 'x'
operation = ' '.join(['lambda x: x', text[-2], text[-1]])
barrel[(active, 'operation')] = eval(operation)
elif text[0] == 'Test:':
barrel[(active, 'test')] = int(text[-1])
elif text[0] == 'If':
action = barrel.get((active, 'action'), [None, None])
if text[1] == 'false:':
action[0] = text[-1]
else:
action[1] = text[-1]
barrel[(active, 'action')] = action
counts = {}
for _ in range(20):
for active in monkeys:
while barrel[(active, 'items')]:
counts[active] = counts.get(active, 0) + 1
item = barrel[(active, 'items')].pop(0)
worry = barrel[(active, 'operation')](item) // 3
i = int(worry % barrel[(active, 'test')] == 0)
sendto = barrel[(active, 'action')][i]
barrel[(sendto, 'items')].append(worry)
highest = list(counts.values())
highest.sort(reverse=True)
print(highest[0] * highest[1])
Part Two
""" day_11_02.py """
# usage: python3 day_11_02.py < input
import sys
monkeys = []
barrel = {}
lcm = 1
active = None
for line in sys.stdin:
text = line.split()
if not text:
continue
if text[0] == 'Monkey':
active = text[1].removesuffix(':')
monkeys.append(active)
elif text[0] == 'Starting':
barrel[(active, 'items')] = list(map(int,
''.join(text[2:]).split(',')))
elif text[0] == 'Operation:':
if text[-1] == 'old':
text[-1] = 'x'
operation = ' '.join(['lambda x: x', text[-2], text[-1]])
barrel[(active, 'operation')] = eval(operation)
elif text[0] == 'Test:':
divisor = int(text[-1])
lcm *= divisor
barrel[(active, 'test')] = divisor
elif text[0] == 'If':
action = barrel.get((active, 'action'), [None, None])
if text[1] == 'false:':
action[0] = text[-1]
else:
action[1] = text[-1]
barrel[(active, 'action')] = action
counts = {}
for _ in range(10000):
for active in monkeys:
while barrel[(active, 'items')]:
counts[active] = counts.get(active, 0) + 1
item = barrel[(active, 'items')].pop(0)
worry = barrel[(active, 'operation')](item) % lcm
i = int(worry % barrel[(active, 'test')] == 0)
sendto = barrel[(active, 'action')][i]
barrel[(sendto, 'items')].append(worry)
highest = list(counts.values())
highest.sort(reverse=True)
print(highest[0] * highest[1])