|
| 1 | +package me.grison.aoc.y2022 |
| 2 | + |
| 3 | +import me.grison.aoc.* |
| 4 | +import java.math.BigInteger.ONE |
| 5 | + |
| 6 | +class Monkey( |
| 7 | + var id: Int, |
| 8 | + var items: MutableList<Long>, |
| 9 | + var operation: (Long) -> Long, |
| 10 | + var divisible: Long, |
| 11 | + var destinations: Pair<Int, Int> |
| 12 | +) |
| 13 | + |
| 14 | +class Day11 : Day(11, 2022) { |
| 15 | + override fun title() = "Monkey in the Middle" |
| 16 | + |
| 17 | + override fun partOne() = solve(20, parseMonkeys()) { level -> level / 3L } |
| 18 | + |
| 19 | + override fun partTwo() = parseMonkeys().let { monkeys -> |
| 20 | + val lcm = lcm(monkeys) |
| 21 | + solve(10_000, monkeys) { level -> level % lcm } |
| 22 | + } |
| 23 | + |
| 24 | + private fun parseMonkeys(): List<Monkey> { |
| 25 | + val monkeys = mutableListOf<Monkey>() |
| 26 | + |
| 27 | + inputGroups.forEach { monkey -> |
| 28 | + val (id, items, operation, divisible, ok, nok) = monkey.lines() |
| 29 | + val after = operation.after(": ").words() |
| 30 | + val (op, operand) = p(after[3], after[4]) |
| 31 | + monkeys.add( |
| 32 | + Monkey( |
| 33 | + id.firstInt(), |
| 34 | + items.allLongs().toMutableList(), |
| 35 | + { i -> |
| 36 | + when (operand.isDigits()) { |
| 37 | + false -> if (op == "+") i + i else i * i |
| 38 | + true -> if (op == "+") i + operand.toLong() else i * operand.toLong() |
| 39 | + } |
| 40 | + }, |
| 41 | + divisible.allLongs().first(), |
| 42 | + p(ok.firstInt(), nok.firstInt()) |
| 43 | + ) |
| 44 | + ) |
| 45 | + } |
| 46 | + |
| 47 | + return monkeys |
| 48 | + } |
| 49 | + |
| 50 | + private fun lcm(monkeys: List<Monkey>) = |
| 51 | + monkeys.map { it.divisible.toBigInteger() }.fold(ONE) { acc, i -> (acc * i) / acc.gcd(i) }.toLong() |
| 52 | + |
| 53 | + private fun solve(rounds: Int, monkeys: List<Monkey>, newLevel: (Long) -> Long): Long { |
| 54 | + val monkeyBusiness = mutableList(monkeys.size, 0L) |
| 55 | + repeat(rounds) { |
| 56 | + monkeys.forEach { monkey -> |
| 57 | + monkey.items.forEach { item -> |
| 58 | + monkeyBusiness[monkey.id] += 1L |
| 59 | + val level = newLevel(monkey.operation(item)) |
| 60 | + val destination = |
| 61 | + if (level % monkey.divisible == 0L) monkey.destinations.first |
| 62 | + else monkey.destinations.second |
| 63 | + monkeys[destination].items.add(level) |
| 64 | + } |
| 65 | + monkey.items.clear() |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return monkeyBusiness.sorted().takeLast(2).product() |
| 70 | + } |
| 71 | +} |
0 commit comments