Skip to content

Commit

Permalink
[2022][day 11] adding part 2 solution
Browse files Browse the repository at this point in the history
  • Loading branch information
IAjimi committed Dec 11, 2022
1 parent 50ec212 commit 83a8c99
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 39 deletions.
92 changes: 53 additions & 39 deletions 2022/AOC11.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,26 @@
from typing import List, Tuple, Set
from copy import deepcopy
from typing import List, Tuple
import parse

from _utils import read_input, timer, Solution


def process_input(filename: str):
_input = read_input(filename)
_input = [line for line in _input if line != ""]
monkeys = [Monkey(*_input[i : i + 6]) for i in range(0, len(_input), 6)]
return monkeys
from _utils import read_input, timer, Solution, product


class Monkey:
def __init__(self, monkey_id, items, operation_str, test_val, monkey1, monkey2):
self._id = int(monkey_id.replace("Monkey ", "").replace(":", ""))
items = items.replace("Starting items: ", "").strip()
self.items = list(map(int, items.split(",")))
self.operation = self.parse_operation(operation_str)
self.test_val = int(test_val.replace("Test: divisible by", "").strip())
self.monkey1 = int(monkey1.replace("If true: throw to monkey", "").strip())
self.monkey2 = int(monkey2.replace("If false: throw to monkey", "").strip())
def __init__(
self,
monkey_id: str,
items: str,
operation: str,
test_val: str,
monkey1: str,
monkey2: str,
):
self._id = parse.parse("Monkey {:d}:", monkey_id)[0]
self.items = list(map(int, items.replace("Starting items: ", "").split(",")))
self.operation = self.parse_operation(operation)
self.test_val = parse.parse("Test: divisible by {:d}", test_val)[0]
self.monkey1 = parse.parse("If true: throw to monkey {:d}", monkey1)[0]
self.monkey2 = parse.parse("If false: throw to monkey {:d}", monkey2)[0]
self.items_inspected = 0

def __repr__(self):
Expand All @@ -28,53 +30,65 @@ def parse_operation(self, operation_str: str):
if "old * old" in operation_str:
return lambda x: x ** 2
elif "*" in operation_str:
operation_val = operation_str.replace("Operation: new = old *", "").strip()
return lambda x: x * int(operation_val)
operation_val = parse.parse("Operation: new = old * {:d}", operation_str)[0]
return lambda x: x * operation_val
elif "+" in operation_str:
operation_val = parse.parse("Operation: new = old + {:d}", operation_str)[0]
return lambda x: x + operation_val
else:
operation_val = operation_str.replace("Operation: new = old +", "").strip()
return lambda x: x + int(operation_val)
raise NotImplementedError

def test_object(self, worry_level: int) -> int:
return self.monkey1 if worry_level % self.test_val == 0 else self.monkey2

def take_turns(self):
item_moves = []

for worry_level in self.items:
new_worry_level = self.operation(worry_level) // 3
item_recipient = self.test_object(new_worry_level)
item_moves.append((item_recipient, new_worry_level))
def inspect_object(self, modulo: int, part1: bool) -> Tuple[int, int]:
worry_level = self.operation(self.items.pop()) % modulo
if part1:
worry_level = worry_level // 3
item_recipient = self.test_object(worry_level)
return item_recipient, worry_level

def take_turn(self, modulo: int, part1: bool) -> List[Tuple[int, int]]:
item_moves = []
self.items_inspected += len(self.items)

while self.items:
item_recipient, worry_level = self.inspect_object(modulo, part1)
item_moves.append((item_recipient, worry_level))

return item_moves


def simulate(monkeys, n_rounds):
items_inspected = [0 for m in monkeys]
def process_input(filename: str) -> List[Monkey]:
_input = read_input(filename)
_input = [line.strip() for line in _input if line != ""]
monkeys = [Monkey(*_input[i : i + 6]) for i in range(0, len(_input), 6)]
return monkeys


def simulate(monkeys: List[Monkey], part1: bool) -> int:
modulo = product([m.test_val for m in monkeys])
n_rounds = 20 if part1 else 10_000

for r in range(n_rounds):
for m in monkeys:
items_inspected[m._id] += len(m.items)
item_moves = m.take_turns()
m.items = []
item_moves = m.take_turn(modulo, part1)
for monkey_id, worry_level in item_moves:
monkeys[monkey_id].items.append(worry_level)

items_inspected.sort()
print(items_inspected)
return items_inspected[-1] * items_inspected[-2]
first, second, *_ = sorted([m.items_inspected for m in monkeys], reverse=True)
return first * second


@timer
def main(filename: str) -> Solution:
monkeys = process_input(filename)
part_1_solution = simulate(monkeys, n_rounds=20)
part_2_solution = 0 # simulate(monkeys, n_rounds=1000)
part_1_solution = simulate(deepcopy(monkeys), part1=True)
part_2_solution = simulate(monkeys, part1=False)
return part_1_solution, part_2_solution


if __name__ == "__main__":
part_1_solution, part_2_solution = main("aoc11.txt")
print(f"PART 1: {part_1_solution}") # 64032
print(f"PART 2: {part_2_solution}") #
print(f"PART 2: {part_2_solution}") # 12729522272
1 change: 1 addition & 0 deletions 2022/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ This repository contains Python solutions to the 2022 edition of [Advent of Code
| [8](https://adventofcode.com/2022/day/8) | **Treetop Tree House** | [:star::star:](https://github.com/IAjimi/AdventOfCode/blob/master/2022/AOC08.py) |
| [9](https://adventofcode.com/2022/day/9) | **Rope Bridge** | [:star::star:](https://github.com/IAjimi/AdventOfCode/blob/master/2022/AOC09.py) |
| [10](https://adventofcode.com/2022/day/10) | **Cathode-Ray Tube** | [:star::star:](https://github.com/IAjimi/AdventOfCode/blob/master/2022/AOC10.py) |
| [11](https://adventofcode.com/2022/day/11) | **Monkey in the Middle** | [:star::star:](https://github.com/IAjimi/AdventOfCode/blob/master/2022/AOC11.py) |

0 comments on commit 83a8c99

Please sign in to comment.