From 0f1e145b80813ae2331b7dac5ace0c589654ad2a Mon Sep 17 00:00:00 2001 From: tchojnacki Date: Thu, 11 Aug 2022 19:24:23 +0200 Subject: Move subproject to avoid IntelliJ module name issues --- aoc-2021-kotlin/src/Day02.kt | 56 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 aoc-2021-kotlin/src/Day02.kt (limited to 'aoc-2021-kotlin/src/Day02.kt') diff --git a/aoc-2021-kotlin/src/Day02.kt b/aoc-2021-kotlin/src/Day02.kt new file mode 100644 index 0000000..2eb085a --- /dev/null +++ b/aoc-2021-kotlin/src/Day02.kt @@ -0,0 +1,56 @@ +object Day02 { + private fun dispatchCommands(commands: List, 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): 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): 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)) +} -- cgit v1.2.3