Skip to content

Commit

Permalink
2023 day 1 improved
Browse files Browse the repository at this point in the history
  • Loading branch information
dkhawk committed Dec 1, 2023
1 parent 02caa2d commit 77cd71c
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/main/kotlin/aoc2023/day01/Day.kt
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,34 @@ class Day(private val scope: CoroutineScope) {
"nine",
)

private val numberMap = mapOf(
"zero" to 0,
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9,

"0" to 0,
"1" to 1,
"2" to 2,
"3" to 3,
"4" to 4,
"5" to 5,
"6" to 6,
"7" to 7,
"8" to 8,
"9" to 9,
)

fun part2() {
part2b()

return
val answer = input.map { line ->
firstDigit(line) to lastDigit(line)
}.sumOf { (a, b) ->
Expand All @@ -76,6 +103,18 @@ class Day(private val scope: CoroutineScope) {
println(answer)
}

fun part2b() {
val answer = input.sumOf { line ->
val a = line.findAnyOf(numberMap.keys)?.second?.let { numberMap.getValue(it) }
?: throw Exception("Failed to find digit in $line")
val b = line.findLastAnyOf(numberMap.keys)?.second?.let { numberMap.getValue(it) }
?: throw Exception("Failed to find digit in $line")
a * 10 + b
}

println(answer)
}

private fun firstDigit(input: String): Int {
val words = numbers
input.indices.forEach { index ->
Expand Down

0 comments on commit 77cd71c

Please sign in to comment.