1
0
Fork 0

day(02): refactor

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2021-12-04 15:54:39 +01:00
parent e3e721b6b4
commit 91aa2e41b7

View file

@ -6,11 +6,10 @@ enum class Command {
FORWARD, DOWN, UP FORWARD, DOWN, UP
} }
fun main() { data class Position(val horizontal: Int = 0, val depth: Int = 0, val aim: Int = 0)
data class Position(val horizontal: Int = 0, val depth: Int = 0, val aim: Int = 0) data class Instruction(val type: Command, val value: Int)
data class Instruction(val type: Command, val value: Int)
fun parseInstruction(instruction: String): Instruction { fun parseInstruction(instruction: String): Instruction {
val splitLine = instruction.split(' ') val splitLine = instruction.split(' ')
check(splitLine.size == 2) check(splitLine.size == 2)
@ -21,13 +20,11 @@ fun main() {
"up" -> return Instruction(Command.UP, value) "up" -> return Instruction(Command.UP, value)
} }
throw IllegalArgumentException("Cannot parse instruction") throw IllegalArgumentException("Cannot parse instruction")
} }
fun toCommands(input: List<String>): List<Instruction> { fun toCommands(input: List<String>): List<Instruction> = input.map { parseInstruction(it) }
return input.map { parseInstruction(it) }
}
fun part1(input: List<Instruction>): Int { fun part1(input: List<Instruction>): Int {
val finalPosition = input.fold(Position()) { pos, instruction -> val finalPosition = input.fold(Position()) { pos, instruction ->
when (instruction.type) { when (instruction.type) {
Command.FORWARD -> pos.copy(horizontal = pos.horizontal + instruction.value) Command.FORWARD -> pos.copy(horizontal = pos.horizontal + instruction.value)
@ -36,9 +33,9 @@ fun main() {
} }
} }
return finalPosition.horizontal * finalPosition.depth return finalPosition.horizontal * finalPosition.depth
} }
fun part2(input: List<Instruction>): Int { fun part2(input: List<Instruction>): Int {
val finalPosition = input.fold(Position()) { pos, instruction -> val finalPosition = input.fold(Position()) { pos, instruction ->
when (instruction.type) { when (instruction.type) {
Command.FORWARD -> pos.copy( Command.FORWARD -> pos.copy(
@ -50,9 +47,9 @@ fun main() {
} }
} }
return finalPosition.horizontal * finalPosition.depth return finalPosition.horizontal * finalPosition.depth
} }
fun main() {
val testInput = toCommands(readInput(2, "test_input")) val testInput = toCommands(readInput(2, "test_input"))
val input = toCommands(readInput(2, "input")) val input = toCommands(readInput(2, "input"))