1
1
package day11
2
2
3
+ import shared.extractLongs
3
4
import java.lang.RuntimeException
4
5
import java.util.LinkedList
5
6
6
7
class Day11 {
7
8
8
9
companion object {
9
10
10
- private val MATCH_NUMBERS = Regex (" [0-9]+" )
11
-
12
11
fun part1 (input : String ): Long {
13
12
val monkeys = parseInput(input).associateBy(Monkey ::id)
14
- return startGame(monkeys, 20 , 3 )
13
+ return startGame(monkeys, 20 ) { it / 3 }
15
14
}
16
15
17
16
fun part2 (input : String ): Long {
18
17
val monkeys = parseInput(input).associateBy(Monkey ::id)
19
- return startGame(monkeys, 10_000 , 1 )
20
- }
21
18
22
- private fun startGame (monkeys : Map <Int , Monkey >, rounds : Int , reliefModifier : Int ): Long {
23
- val commonDenominator = monkeys.values
24
- .map(Monkey ::divisibleValue)
25
- .reduce { acc, v -> acc * v }
19
+ val commonDenominator = monkeys.values
20
+ .map(Monkey ::divisibleValue)
21
+ .reduce { acc, v -> acc * v }
22
+
23
+ return startGame(monkeys, 10_000 ) { it % commonDenominator }
24
+ }
26
25
26
+ private fun startGame (monkeys : Map <Int , Monkey >, rounds : Int , reliefOperation : ReliefOperation ): Long {
27
27
for (round in 1 .. rounds) {
28
28
monkeys.forEach { (_, monkey) ->
29
29
monkey.items.forEach { item ->
30
- val newWorryLevel = (monkey.inspectItem(item) / reliefModifier) % commonDenominator
30
+ val newWorryLevel = reliefOperation (monkey.inspectItem(item))
31
31
val newMonkeyId = monkey.chooseTargetMonkey(newWorryLevel)
32
32
33
33
monkeys[newMonkeyId]?.items?.add(newWorryLevel)
@@ -73,7 +73,8 @@ class Day11 {
73
73
input.split(" \n\n " ).mapIndexed { i, value ->
74
74
val lines = value.split(" \n " ).map(String ::trimIndent)
75
75
76
- val items = parseItems(lines[1 ])
76
+ // Parse: Starting items: 79, 98
77
+ val items = lines[1 ].extractLongs()
77
78
val operation = parseOperation(lines[2 ])
78
79
val test = parseTest(lines[3 ], lines[4 ], lines[5 ])
79
80
val divisibleValue = lines[3 ].split(" " ).last().toInt()
@@ -84,13 +85,6 @@ class Day11 {
84
85
return monkeys
85
86
}
86
87
87
- // Parse: Starting items: 79, 98
88
- private fun parseItems (input : String ): List <Long > {
89
- return MATCH_NUMBERS .findAll(input).map {
90
- it.value.toLong()
91
- }.toList()
92
- }
93
-
94
88
// Parse: Operation: new = old * 19
95
89
private fun parseOperation (input : String ): MonkeyOperation {
96
90
val parts = input.split(" " )
@@ -138,4 +132,5 @@ class Day11 {
138
132
}
139
133
140
134
typealias MonkeyOperation = (value: Long ) -> Long
141
- typealias MonkeyTest = (value: Long ) -> Int
135
+ typealias MonkeyTest = (value: Long ) -> Int
136
+ typealias ReliefOperation = (value: Long ) -> Long
0 commit comments