-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay02Dive.kt
59 lines (50 loc) · 1.99 KB
/
Day02Dive.kt
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
package adventofcode.year2021
import adventofcode.Puzzle
import adventofcode.PuzzleInput
import adventofcode.year2021.Day02Dive.Companion.Direction.DOWN
import adventofcode.year2021.Day02Dive.Companion.Direction.FORWARD
import adventofcode.year2021.Day02Dive.Companion.Direction.UP
class Day02Dive(customInput: PuzzleInput? = null) : Puzzle(customInput) {
override val name = "Dive!"
private val commands by lazy { input.lines().map(::Command) }
override fun partOne() =
commands.fold(Position()) { acc, command ->
when (command.direction) {
FORWARD -> acc.copy(horizontal = acc.horizontal + command.value)
DOWN -> acc.copy(depth = acc.depth + command.value)
UP -> acc.copy(depth = acc.depth - command.value)
}
}.multiply()
override fun partTwo() =
commands.fold(Position()) { acc, command ->
when (command.direction) {
FORWARD -> acc.copy(horizontal = acc.horizontal + command.value, depth = acc.depth + acc.aim * command.value)
DOWN -> acc.copy(aim = acc.aim + command.value)
UP -> acc.copy(aim = acc.aim - command.value)
}
}.multiply()
companion object {
private data class Position(
val horizontal: Int = 0,
val depth: Int = 0,
val aim: Int = 0,
) {
fun multiply() = horizontal * depth
}
private data class Command(
val direction: Direction,
val value: Int,
) {
constructor(input: String) : this(Direction(input.split(" ").first()), input.split(" ").last().toInt())
}
private enum class Direction(val direction: String) {
FORWARD("forward"),
DOWN("down"),
UP("up"),
;
companion object {
operator fun invoke(direction: String) = entries.associateBy(Direction::direction)[direction]!!
}
}
}
}