day(07): add solution
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
238df0614e
commit
a92bf3b96f
2 changed files with 30 additions and 0 deletions
29
src/day07/Day07.kt
Normal file
29
src/day07/Day07.kt
Normal file
|
@ -0,0 +1,29 @@
|
||||||
|
package day07
|
||||||
|
|
||||||
|
import readInputAsCommaSeparatedInts
|
||||||
|
import kotlin.math.absoluteValue
|
||||||
|
|
||||||
|
// for part 1, it's always included in the input set
|
||||||
|
fun part1(input: List<Int>): Int = input.toSet().minOf { target ->
|
||||||
|
input.sumOf {
|
||||||
|
(it - target).absoluteValue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun part2(input: List<Int>): Int = (input.minOrNull()!!..input.maxOrNull()!!).minOf { target ->
|
||||||
|
input.sumOf {
|
||||||
|
val diff = (it - target).absoluteValue
|
||||||
|
diff * (diff + 1) / 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun main() {
|
||||||
|
val testInput = readInputAsCommaSeparatedInts(7, "test_input").sorted()
|
||||||
|
val input = readInputAsCommaSeparatedInts(7, "input").sorted()
|
||||||
|
|
||||||
|
check(part1(testInput) == 37)
|
||||||
|
println(part1(input))
|
||||||
|
|
||||||
|
check(part2(testInput) == 168)
|
||||||
|
println(part2(input))
|
||||||
|
}
|
1
src/day07/test_input.txt
Normal file
1
src/day07/test_input.txt
Normal file
|
@ -0,0 +1 @@
|
||||||
|
16,1,2,0,4,2,7,1,2,14
|
Loading…
Reference in a new issue