Improved solution to day 1.

This commit is contained in:
Chris Hodges 2023-12-01 19:06:02 +01:00
parent 99a47fdf75
commit d7ac6a2506

View File

@ -58,35 +58,24 @@ zoneight234
""" """
fun part1(input: List<String>): Int { fun part1(input: List<String>): 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 digitStrings = arrayOf("---", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
val digitStringsRev = digitStrings.map { it.reversed() }.toTypedArray()
fun findAll(s: String): List<Pair<Int, Int>> { fun findFirst(s: String, digs: Array<String>): Int {
val results = ArrayList<Pair<Int, Int>>() for (p in s.indices) {
for ((dig, l) in digitStrings.withIndex()) { if (s[p].isDigit()) return s[p].digitToInt()
var sp = 0 val m = s.subSequence(p, s.length)
do { val match = digs.withIndex().firstOrNull { m.startsWith(it.value) }
val fp = s.indexOf(l, sp) if (match != null) return match.index
if (fp < 0) break
sp = fp + 1
results.add(fp to dig)
} while (true)
} }
return results return -1
} }
fun part2(input: List<String>): Int { fun part2(input: List<String>): Int {
return input.sumOf { return input.sumOf { findFirst(it, digitStrings) * 10 + findFirst(it.reversed(), digitStringsRev) }
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()
}
} }
// test if implementation meets criteria from the description, like: // test if implementation meets criteria from the description, like: