📜 Day 01 - Historian Hysteria Link to heading
Day 1 is always simple and a nice beginning for the upcomming challenges which will get out of hand very fast, and this year is no exception:
We have a long list split of Int
s split into two columns:
3 4
4 3
2 5
1 3
3 9
3 3
And, funny enough, the hardest part of todays Puzzle was to parse out the Two lists from this unusual notation, but with some weird use of map and let it can be done easily:
val list1 = mutableListOf<Int>()
val list2 = mutableListOf<Int>()
val input = Path("Day01.txt")
.readLines()
.map {
it.split(" ")
.let {
it[0].toInt() to it[1].toInt()
}
}
input.forEach {
list1.add(it.first)
list2.add(it.second)
}
Part One Link to heading
Part one is pretty straightforward: Combine the smallest number of the left list with the smallest one of the right list, calculate the distance between those two numbers, rinse and repeat for all pairs and return the sum of all rows.
For this task, I decided to translate the two lists into one list of Pair<Int,Int>
, which I’ve done using kotlin’s List<T>.zip(t:List<T>)
:
val pairs = list1.sorted().zip(list2.sorted())
Then, to actually compute the distances, I used another of Kotlins extension functions: List<T>.sumOf(block: (T) -> Int)
: Iterate over all elements of the list, store the result of the lambda, sum all of them together and return the result. To calculate the distance itself, we can just subtract the values and take the absolute value of it, which will always result in the right value:
pairs.sumOf { abs(it.first - it.second) }
Which prints 11
for the test input at the top of the page.
Part Two Link to heading
Part two was also done pretty easily, iterate over the left list, multiply each number by the amount of occurences of it in the right list, and sum all of these again. For this, I opted not to use my built pairs but the lists directly, and just looped over them using sumOf { }
again:
list1.sumOf { it * list2.count { p -> p == it } }
Which outputs 31
.
Today was a pretty simple day, but that was to be expected from Day 1. I’m very excited for the next days, Advent of Code is always very fun!