part 1
5.02 µs
warm-up 4.2x faster once warm
4 KB allocated per run
kotlin puzzle ↗
part 1
5.02 µs
warm-up 4.2x faster once warm
4 KB allocated per run
part 2
22.5 µs
warm-up 11.4x faster once warm
11 KB allocated per run
package day02
import aoc.*
enum class Color(val letter: Char) {
RED('r'),
ORANGE('o'),
YELLOW('y'),
GREEN('g'),
BLUE('b'),
VIOLET('v')
}
fun Char.toColor(): Color = Color.entries.first { it.letter == this }
fun Color.distance(next: Color): Int {
val diff = next.ordinal - this.ordinal
if (diff > 0) return diff
return diff + Color.entries.size
}
fun part1(input: String): Any? {
val program = input.map { it.toColor() }
var current = Color.RED
var distance = 0
for (color in program) {
distance += current.distance(color)
current = color
}
return distance
}
fun part2(input: String): Any? {
val program = input.map { it.toColor() }.groupingBy { it }.eachCount().toMutableMap()
var current = Color.RED
var distance = 0
while (program.isNotEmpty()) {
val nextColor = program.maxBy { current.distance(it.key) }
distance += current.distance(nextColor.key)
current = nextColor.key
program.computeIfPresent(nextColor.key) { _, v -> (v -1).takeIf { it > 0 } }
}
return distance
}
fun main() = solve(2)