aboutsummaryrefslogtreecommitdiff
path: root/2021-kotlin/src/Day02.kt
diff options
context:
space:
mode:
authortchojnacki <tomaszchojnacki2001@gmail.com>2022-08-11 12:01:44 +0200
committertchojnacki <tomaszchojnacki2001@gmail.com>2022-08-11 12:01:44 +0200
commit34c2414304d59e76d52b96efe6bebebb4e75f086 (patch)
tree2b78254a2a909521993caa459b24ab68fae43324 /2021-kotlin/src/Day02.kt
parent8742021f42d2c5417abad25bfdb6d7abbf6e759e (diff)
downloadgleam_aoc2020-34c2414304d59e76d52b96efe6bebebb4e75f086.tar.gz
gleam_aoc2020-34c2414304d59e76d52b96efe6bebebb4e75f086.zip
Move year 2021 into a subfolder
Diffstat (limited to '2021-kotlin/src/Day02.kt')
-rw-r--r--2021-kotlin/src/Day02.kt56
1 files changed, 56 insertions, 0 deletions
diff --git a/2021-kotlin/src/Day02.kt b/2021-kotlin/src/Day02.kt
new file mode 100644
index 0000000..2eb085a
--- /dev/null
+++ b/2021-kotlin/src/Day02.kt
@@ -0,0 +1,56 @@
+object Day02 {
+ private fun dispatchCommands(commands: List<String>, action: (command: String, argument: Int) -> Unit) {
+ for (line in commands) {
+ val parts = line.split(" ")
+ val command = parts[0]
+ val argument = parts[1].toInt()
+
+ action(command, argument)
+ }
+ }
+
+ fun part1(input: List<String>): Int {
+ var horizontal = 0
+ var depth = 0
+
+ dispatchCommands(input) { command, argument ->
+ when (command) {
+ "forward" -> horizontal += argument
+ "down" -> depth += argument
+ "up" -> depth -= argument
+ }
+ }
+
+ return horizontal * depth
+ }
+
+ fun part2(input: List<String>): Int {
+ var horizontal = 0
+ var depth = 0
+ var aim = 0
+
+ dispatchCommands(input) { command, argument ->
+ when (command) {
+ "forward" -> {
+ horizontal += argument
+ depth += aim * argument
+ }
+
+ "down" -> aim += argument
+ "up" -> aim -= argument
+ }
+ }
+
+ return horizontal * depth
+ }
+}
+
+fun main() {
+ val testInput = readInputAsLines("Day02_test")
+ check(Day02.part1(testInput) == 150)
+ check(Day02.part2(testInput) == 900)
+
+ val input = readInputAsLines("Day02")
+ println(Day02.part1(input))
+ println(Day02.part2(input))
+}