day(01): solve first day
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
47da5f8507
commit
78e3a42c4b
2 changed files with 43 additions and 14 deletions
6
inputs/day01/sample.txt
Normal file
6
inputs/day01/sample.txt
Normal file
|
@ -0,0 +1,6 @@
|
||||||
|
3 4
|
||||||
|
4 3
|
||||||
|
2 5
|
||||||
|
1 3
|
||||||
|
3 9
|
||||||
|
3 3
|
51
src/Day01.kt
51
src/Day01.kt
|
@ -1,21 +1,44 @@
|
||||||
|
fun parseInput(inputType: String): Pair<MutableList<Int>, MutableList<Int>> =
|
||||||
|
readInput(1, inputType).fold(mutableListOf<Int>() to mutableListOf<Int>()) { (left, right), line ->
|
||||||
|
val nums = line.split(Regex("\\s+"))
|
||||||
|
|
||||||
|
left.add(nums[0].toInt())
|
||||||
|
right.add(nums[1].toInt())
|
||||||
|
|
||||||
|
left to right
|
||||||
|
}
|
||||||
|
|
||||||
|
fun precompute(input: Pair<MutableList<Int>, MutableList<Int>>) {
|
||||||
|
input.first.sort()
|
||||||
|
input.second.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) }
|
||||||
|
}
|
||||||
|
|
||||||
fun main() {
|
fun main() {
|
||||||
fun part1(input: List<String>): Int {
|
// Test of sample
|
||||||
return input.size
|
val testInput = parseInput("sample")
|
||||||
}
|
precompute(testInput)
|
||||||
|
|
||||||
fun part2(input: List<String>): Int {
|
check(part1(testInput) == 11)
|
||||||
return input.size
|
check(part2(testInput) == 31)
|
||||||
}
|
|
||||||
|
|
||||||
// Test if implementation meets criteria from the description, like:
|
// Challenge input
|
||||||
check(part1(listOf("test_input")) == 1)
|
val input = parseInput("input")
|
||||||
|
precompute(input)
|
||||||
|
|
||||||
// Or read a large test input from the `src/Day01_test.txt` file:
|
|
||||||
val testInput = readInput("Day01_test")
|
|
||||||
check(part1(testInput) == 1)
|
|
||||||
|
|
||||||
// Read the input from the `src/Day01.txt` file.
|
|
||||||
val input = readInput("Day01")
|
|
||||||
part1(input).println()
|
part1(input).println()
|
||||||
part2(input).println()
|
part2(input).println()
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue