Skip to content

Commit de27dbb

Browse files
committed
add solution for day 2
1 parent 6a3c52e commit de27dbb

File tree

5 files changed

+1090
-1
lines changed

5 files changed

+1090
-1
lines changed

src/main/kotlin/advent2021/Day02.kt

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package advent2021
2+
3+
import Resources
4+
import advent2021.Day02.DIRECTIVE.DOWN
5+
import advent2021.Day02.DIRECTIVE.FORWARD
6+
import advent2021.Day02.DIRECTIVE.UP
7+
8+
class Day02(input: List<String>) {
9+
10+
private val commands = input.map { Command.of(it) }
11+
12+
private enum class DIRECTIVE { FORWARD, UP, DOWN }
13+
14+
private class Command(val directive: DIRECTIVE, val amount: Int) {
15+
companion object {
16+
fun of(input: String) = input.split(" ").let {
17+
Command(
18+
directive = DIRECTIVE.valueOf(it.first().uppercase()),
19+
amount = it.last().toInt()
20+
)
21+
}
22+
}
23+
}
24+
25+
private data class Submarine(
26+
val depth: Int = 0,
27+
val position: Int = 0,
28+
val aim: Int = 0
29+
) {
30+
fun answer() = depth * position
31+
32+
fun movePart1(command: Command): Submarine =
33+
when (command.directive) {
34+
FORWARD -> copy(position = position + command.amount)
35+
DOWN -> copy(depth = depth + command.amount)
36+
UP -> copy(depth = depth - command.amount)
37+
}
38+
39+
fun movePart2(command: Command) =
40+
when (command.directive) {
41+
FORWARD -> copy(
42+
position = position + command.amount,
43+
depth = depth + (aim * command.amount)
44+
)
45+
DOWN -> copy(aim = aim + command.amount)
46+
UP -> copy(aim = aim - command.amount)
47+
}
48+
}
49+
50+
fun solvePart1(): Int =
51+
commands.fold(Submarine()) { submarine, command -> submarine.movePart1(command) }.answer()
52+
53+
fun solvePart2(): Int =
54+
commands.fold(Submarine()) { submarine, command -> submarine.movePart2(command) }.answer()
55+
}
56+
57+
fun main() {
58+
val input = Resources.resourceAsListOfString("advent2021/day02.txt")
59+
val day = Day02(input = input)
60+
println("Part 1: ${day.solvePart1()}")
61+
println("Part 2: ${day.solvePart2()}")
62+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy