Introduction
Today's have a ton of possible solutions! Let's watch two ways in this post. The first one will be "the logical" way while the second will be more focused on Kotlin and functional programming.
Problem Input
Now our submarine can take the following commands forward
, down
, up
.
First, we will have to parse the list of received commands. To do this feel free to look at how it is done in the Utils.kt
file.
Version 1
Part 1
Problem
Here the code is kinda straight forward. There is no much to explain. Maybe we can talk about array using destructing.
So, in Kotlin (as in JavaScript, Python...), we can easily destructuring an array / object. Given we have the following array arr = [1, 2, 3]
, if we want to access these values, we should use their indexes:
val arr = [1, 2, 3]
val a = arr[0]
val b = arr[1]
val c = arr[2]
Whereas using destructuration, we can have:
val (a, b, c) = [1, 2, 3]
This is exactly what I've done for splitting the command and it's value.
Solution
fun part1(input: List<String>): Int {
var height = 0
var depth = 0
for (line in input) {
val (command, step) = line.split(" ")
when (command) {
"forward" -> height += step.toInt()
"down" -> depth += step.toInt()
"up" -> depth -= step.toInt()
}
}
return height * depth
}
Part 2
Problem
The second part only add a new variable, but the main "logic" is still the same.
Solution
fun part2(input: List<String>): Int {
var height = 0
var depth = 0
var aim = 0
for (line in input) {
val (command, step) = line.split(" ")
when (command) {
"forward" -> {
height += step.toInt()
depth += aim * step.toInt()
}
"down" -> aim += step.toInt()
"up" -> aim -= step.toInt()
}
}
return height * depth
}
Conclusion
An easy one, still nice to remember about object / array destructuring.
+ 2 ⭐️ !!!
Useful links
- Introduction – The introduction of this project.
- https://kotlinlang.org – Kotlin official website.
- https://github.com/triozer/aoc-2021-in-kotlin – My solutions and tests for each day.