generated from kotlin-hands-on/advent-of-code-kotlin-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay02.kt
86 lines (72 loc) · 2.08 KB
/
Day02.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
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 year2021.`02`
import readInput
private enum class Command {
Forward,
Down,
Up;
}
private data class CommandWrapper(
val command: Command,
val amount: Int,
)
fun main() {
fun parse(input: List<String>): List<CommandWrapper> {
return input
.map {
val (command, amount) = it.split(" ")
val result = when (command) {
"forward" -> Command.Forward
"down" -> Command.Down
"up" -> Command.Up
else -> error("Illegal State $command")
}
CommandWrapper(result, amount.toInt())
}
}
fun part1(input: List<String>): Int {
var horizontal = 0
var depth = 0
parse(input)
.forEach { (command, amount) ->
when (command) {
Command.Forward -> {
horizontal += amount
}
Command.Up -> {
depth -= amount
}
Command.Down -> {
depth += amount
}
}
}
return horizontal * depth
}
fun part2(input: List<String>): Int {
var aim = 0
var horizontal = 0
var depth = 0
parse(input)
.forEach { (command, amount) ->
when (command) {
Command.Forward -> {
horizontal += amount
depth += aim * amount
}
Command.Up -> {
aim -= amount
}
Command.Down -> {
aim += amount
}
}
}
return horizontal * depth
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 150)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}