day(01): convert to the solution using abstract class
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
a29c0008d8
commit
273204ca6b
1 changed files with 37 additions and 34 deletions
71
src/Day01.kt
71
src/Day01.kt
|
@ -1,44 +1,47 @@
|
||||||
fun parseInput(inputType: String): Pair<MutableList<Int>, MutableList<Int>> =
|
class Day01(
|
||||||
readInput(1, inputType).fold(mutableListOf<Int>() to mutableListOf<Int>()) { (left, right), line ->
|
inputType: String,
|
||||||
val nums = line.split(Regex("\\s+"))
|
) : Day<Int, Int>() {
|
||||||
|
private val left: MutableList<Int>
|
||||||
|
private val right: MutableList<Int>
|
||||||
|
|
||||||
left.add(nums[0].toInt())
|
init {
|
||||||
right.add(nums[1].toInt())
|
val (left, right) =
|
||||||
|
readInput(
|
||||||
|
1,
|
||||||
|
inputType,
|
||||||
|
).fold(mutableListOf<Int>() to mutableListOf<Int>()) { (left, right), line ->
|
||||||
|
val nums = line.split(Regex("\\s+"))
|
||||||
|
|
||||||
left to right
|
left.add(nums[0].toInt())
|
||||||
|
right.add(nums[1].toInt())
|
||||||
|
|
||||||
|
left to right
|
||||||
|
}
|
||||||
|
|
||||||
|
this.left = left
|
||||||
|
this.right = right
|
||||||
}
|
}
|
||||||
|
|
||||||
fun precompute(input: Pair<MutableList<Int>, MutableList<Int>>) {
|
override fun precompute() {
|
||||||
input.first.sort()
|
left.sort()
|
||||||
input.second.sort()
|
right.sort()
|
||||||
}
|
|
||||||
|
|
||||||
fun part1(input: Pair<List<Int>, List<Int>>): Int =
|
|
||||||
input.first.zip(input.second).sumOf { (l, r) -> maxOf(l - r, r - l) }
|
|
||||||
|
|
||||||
fun part2(input: Pair<List<Int>, List<Int>>): Int {
|
|
||||||
val (left, right) = input
|
|
||||||
val freqs = buildMap<Int, Int> {
|
|
||||||
right.forEach { it ->
|
|
||||||
put(it, 1 + getOrDefault(it, 0))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return left.sumOf { it -> it * freqs.getOrDefault(it, 0) }
|
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() {
|
fun main() {
|
||||||
// Test of sample
|
Day01("sample").test(11, 31)
|
||||||
val testInput = parseInput("sample")
|
Day01("input").run()
|
||||||
precompute(testInput)
|
|
||||||
|
|
||||||
check(part1(testInput) == 11)
|
|
||||||
check(part2(testInput) == 31)
|
|
||||||
|
|
||||||
// Challenge input
|
|
||||||
val input = parseInput("input")
|
|
||||||
precompute(input)
|
|
||||||
|
|
||||||
part1(input).println()
|
|
||||||
part2(input).println()
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue