generated from Jadarma/advent-of-code-kotlin-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathY2023D01.kt
39 lines (32 loc) · 1.56 KB
/
Y2023D01.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package aockt.y2023
import aockt.util.parse
import io.github.jadarma.aockt.core.Solution
object Y2023D01 : Solution {
/** A map from digit symbols and spellings to their numerical values. */
private val textToDigit: Map<String, Int> = buildMap {
listOf("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
.forEachIndexed { value, text ->
put(value.toString(), value)
put(text, value)
}
}
/**
* Processes a modified calibration string and extracts the original calibration number.
* @param acceptSpelling Whether to accept spelled-out digits. If false, only numerical notation is considered.
*/
private fun String.normalizeCalibrationNumber(acceptSpelling: Boolean): Int = parse {
val acceptable =
if(acceptSpelling) textToDigit.keys
else textToDigit.keys.filter { it.length == 1 && it.first().isDigit() }
val first = findAnyOf(acceptable)!!.second.let(textToDigit::getValue)
val last = findLastAnyOf(acceptable)!!.second.let(textToDigit::getValue)
first * 10 + last
}
/** Parses the [input], computes the calibration numbers and returns their sum. */
private fun calibrate(input: String, acceptSpelling: Boolean): Int =
input
.lineSequence()
.sumOf { it.normalizeCalibrationNumber(acceptSpelling) }
override fun partOne(input: String) = calibrate(input, acceptSpelling = false)
override fun partTwo(input: String) = calibrate(input, acceptSpelling = true)
}