Improved solution to day 1.
This commit is contained in:
parent
99a47fdf75
commit
d7ac6a2506
@ -58,35 +58,24 @@ zoneight234
|
||||
"""
|
||||
|
||||
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 digitStringsRev = digitStrings.map { it.reversed() }.toTypedArray()
|
||||
|
||||
fun findAll(s: String): List<Pair<Int, Int>> {
|
||||
val results = ArrayList<Pair<Int, Int>>()
|
||||
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<String>): 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<String>): 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:
|
||||
|
Loading…
Reference in New Issue
Block a user