1
0
Fork 0

day(02): add solution

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2021-12-04 14:03:27 +01:00
parent 252617a81d
commit e8673460a2
3 changed files with 1066 additions and 0 deletions

60
src/Day02.kt Normal file
View file

@ -0,0 +1,60 @@
enum class Command {
FORWARD, DOWN, UP
}
fun main() {
data class Position(val horizontal: Int = 0, val depth: Int = 0, val aim: Int = 0)
data class Instruction(val type: Command, val value: Int)
fun parseInstruction(instruction: String): Instruction {
val splitLine = instruction.split(' ')
check(splitLine.size == 2)
val value = splitLine[1].toInt()
when (splitLine[0]) {
"forward" -> return Instruction(Command.FORWARD, value)
"down" -> return Instruction(Command.DOWN, value)
"up" -> return Instruction(Command.UP, value)
}
throw IllegalArgumentException("Cannot parse instruction")
}
fun toCommands(input: List<String>): List<Instruction> {
return input.map { parseInstruction(it) }
}
fun part1(input: List<Instruction>): Int {
val finalPosition = input.fold(Position()) { pos, instruction ->
when (instruction.type) {
Command.FORWARD -> pos.copy(horizontal = pos.horizontal + instruction.value)
Command.UP -> pos.copy(depth = pos.depth - instruction.value)
Command.DOWN -> pos.copy(depth = pos.depth + instruction.value)
}
}
return finalPosition.horizontal * finalPosition.depth
}
fun part2(input: List<Instruction>): Int {
val finalPosition = input.fold(Position()) { pos, instruction ->
when (instruction.type) {
Command.FORWARD -> pos.copy(
horizontal = pos.horizontal + instruction.value,
depth = pos.depth + instruction.value * pos.aim
)
Command.UP -> pos.copy(aim = pos.aim - instruction.value)
Command.DOWN -> pos.copy(aim = pos.aim + instruction.value)
}
}
return finalPosition.horizontal * finalPosition.depth
}
val testInput = toCommands(readInput("Day02_test"))
val input = toCommands(readInput("Day02"))
check(part1(testInput) == 150)
println(part1(input))
check(part2(testInput) == 900)
println(part2(input))
}

1000
src/Day02.txt Normal file

File diff suppressed because it is too large Load diff

6
src/Day02_test.txt Normal file
View file

@ -0,0 +1,6 @@
forward 5
down 5
forward 8
up 3
down 8
forward 2