-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay21MonkeyMath.kt
More file actions
86 lines (75 loc) · 2.83 KB
/
Day21MonkeyMath.kt
File metadata and controls
86 lines (75 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package adventofcode.year2022
import adventofcode.Puzzle
import adventofcode.PuzzleInput
import adventofcode.common.String.containsOnlyDigits
import adventofcode.year2022.Day21MonkeyMath.Companion.Operation.DIV
import adventofcode.year2022.Day21MonkeyMath.Companion.Operation.MINUS
import adventofcode.year2022.Day21MonkeyMath.Companion.Operation.PLUS
import adventofcode.year2022.Day21MonkeyMath.Companion.Operation.TIMES
class Day21MonkeyMath(
customInput: PuzzleInput? = null,
) : Puzzle(customInput) {
private val monkeys by lazy {
input
.lines()
.map { it.split(": ") }
.associate { (name, expression) -> name to Monkey(expression) }
.also { monkeys ->
monkeys
.values
.filterIsInstance<MathMonkey>()
.forEach { monkey ->
monkey.leftMonkey = monkeys[monkey.leftMonkeyName]!!
monkey.rightMonkey = monkeys[monkey.rightMonkeyName]!!
}
}
}
override fun partOne() = monkeys["root"]!!.yell()
companion object {
private enum class Operation(
val operation: String,
) {
PLUS("+"),
MINUS("-"),
TIMES("*"),
DIV("/"),
;
companion object {
operator fun invoke(operation: String) = entries.associateBy(Operation::operation)[operation]!!
}
}
private sealed class Monkey {
abstract fun yell(): Long
companion object {
operator fun invoke(expression: String): Monkey =
when (expression.containsOnlyDigits()) {
true -> NumberMonkey(expression.toLong())
false -> {
val (leftMonkeyName, operation, rightMonkeyName) = expression.split(" ")
MathMonkey(leftMonkeyName, Operation(operation), rightMonkeyName)
}
}
}
}
private class NumberMonkey(
val number: Long,
) : Monkey() {
override fun yell() = number
}
private class MathMonkey(
val leftMonkeyName: String,
val operation: Operation,
val rightMonkeyName: String,
) : Monkey() {
lateinit var leftMonkey: Monkey
lateinit var rightMonkey: Monkey
override fun yell() =
when (operation) {
PLUS -> leftMonkey.yell() + rightMonkey.yell()
MINUS -> leftMonkey.yell() - rightMonkey.yell()
TIMES -> leftMonkey.yell() * rightMonkey.yell()
DIV -> leftMonkey.yell() / rightMonkey.yell()
}
}
}
}