diff --git a/src/aoc2023/Day01.kt b/src/aoc2023/Day01.kt index 5ae728a..3f7ce51 100644 --- a/src/aoc2023/Day01.kt +++ b/src/aoc2023/Day01.kt @@ -58,35 +58,24 @@ zoneight234 """ fun part1(input: List): Int { - return input.sumOf { (it.filter { it.isDigit() }.first().toString() + it.filter { it.isDigit() }.last().toString()).toInt() } + return input.sumOf { (it.first { it.isDigit() }.toString() + it.last { it.isDigit() }.toString()).toInt() } } val digitStrings = arrayOf("---", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine") + val digitStringsRev = digitStrings.map { it.reversed() }.toTypedArray() - fun findAll(s: String): List> { - val results = ArrayList>() - for ((dig, l) in digitStrings.withIndex()) { - var sp = 0 - do { - val fp = s.indexOf(l, sp) - if (fp < 0) break - sp = fp + 1 - results.add(fp to dig) - } while (true) + fun findFirst(s: String, digs: Array): Int { + for (p in s.indices) { + if (s[p].isDigit()) return s[p].digitToInt() + val m = s.subSequence(p, s.length) + val match = digs.withIndex().firstOrNull { m.startsWith(it.value) } + if (match != null) return match.index } - return results + return -1 } fun part2(input: List): Int { - return input.sumOf { - val digitLetters = findAll(it) - val realDigs = it.withIndex() - .filter { i -> i.value.isDigit() } - .map { i -> i.index to i.value.toString().toInt() } - val digits = listOf(digitLetters, realDigs).flatten().sortedBy { it.first } - .map { it.second } - digits.first() * 10 + digits.last() - } + return input.sumOf { findFirst(it, digitStrings) * 10 + findFirst(it.reversed(), digitStringsRev) } } // test if implementation meets criteria from the description, like: