day(01): convert to the solution using abstract class

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-12-02 16:07:45 +01:00
parent a29c0008d8
commit 273204ca6b
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -1,5 +1,15 @@
fun parseInput(inputType: String): Pair<MutableList<Int>, MutableList<Int>> =
readInput(1, inputType).fold(mutableListOf<Int>() to mutableListOf<Int>()) { (left, right), line ->
class Day01(
inputType: String,
) : Day<Int, Int>() {
private val left: MutableList<Int>
private val right: MutableList<Int>
init {
val (left, right) =
readInput(
1,
inputType,
).fold(mutableListOf<Int>() to mutableListOf<Int>()) { (left, right), line ->
val nums = line.split(Regex("\\s+"))
left.add(nums[0].toInt())
@ -8,37 +18,30 @@ fun parseInput(inputType: String): Pair<MutableList<Int>, MutableList<Int>> =
left to right
}
fun precompute(input: Pair<MutableList<Int>, MutableList<Int>>) {
input.first.sort()
input.second.sort()
}
this.left = left
this.right = right
}
fun part1(input: Pair<List<Int>, List<Int>>): Int =
input.first.zip(input.second).sumOf { (l, r) -> maxOf(l - r, r - l) }
override fun precompute() {
left.sort()
right.sort()
}
fun part2(input: Pair<List<Int>, List<Int>>): Int {
val (left, right) = input
val freqs = buildMap<Int, Int> {
override fun part1(): Int = left.zip(right).sumOf { (l, r) -> maxOf(l - r, r - l) }
override fun part2(): Int {
val freqs =
buildMap<Int, Int> {
right.forEach { it ->
put(it, 1 + getOrDefault(it, 0))
}
}
return left.sumOf { it -> it * freqs.getOrDefault(it, 0) }
}
}
fun main() {
// Test of sample
val testInput = parseInput("sample")
precompute(testInput)
check(part1(testInput) == 11)
check(part2(testInput) == 31)
// Challenge input
val input = parseInput("input")
precompute(input)
part1(input).println()
part2(input).println()
Day01("sample").test(11, 31)
Day01("input").run()
}