import kotlin.math.abs
funpart1(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()
}
funpart2(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
}
privatefunparse(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
}
Kotlin
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 }