From 77cd71c6726e91a78d0da1874813c501feda76f6 Mon Sep 17 00:00:00 2001 From: Dale Hawkins Date: Fri, 1 Dec 2023 15:17:33 -0700 Subject: [PATCH] 2023 day 1 improved --- src/main/kotlin/aoc2023/day01/Day.kt | 39 ++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/main/kotlin/aoc2023/day01/Day.kt b/src/main/kotlin/aoc2023/day01/Day.kt index fb767ba..ba652e9 100644 --- a/src/main/kotlin/aoc2023/day01/Day.kt +++ b/src/main/kotlin/aoc2023/day01/Day.kt @@ -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) -> @@ -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 ->