proved_unglue@programming.devtoAdvent Of Code@programming.dev•🌲 - 2024 DAY 1 SOLUTIONS -🌲
1·
22 hours agoKotlin
No 💜 for Kotlin here?
import kotlin.math.abs
fun part1(input: String): Int {
val diffs: MutableList<Int> = mutableListOf()
val pair = parse(input)
pair.first.sort()
pair.second.sort()
pair.first.forEachIndexed { idx, num ->
diffs.add(abs(num - pair.second[idx]))
}
return diffs.sum()
}
fun part2(input: String): Int {
val pair = parse(input)
val frequencies = pair.second.groupingBy { it }.eachCount()
var score = 0
pair.first.forEach { num ->
score += num * frequencies.getOrDefault(num, 0)
}
return score
}
private fun parse(input: String): Pair<MutableList<Int>, MutableList<Int>> {
val left: MutableList<Int> = mutableListOf()
val right: MutableList<Int> = mutableListOf()
input.lines().forEach { line ->
if (line.isNotBlank()) {
val parts = line.split("\\s+".toRegex())
left.add(parts[0].toInt())
right.add(parts[1].toInt())
}
}
return left to right
}
Thanks! I like the
Pair
destruction andzip().sumOf()
approach. I’m relatively new to Kotlin, so this is a good learning experience. 😅