62 lines
1.7 KiB
Kotlin
62 lines
1.7 KiB
Kotlin
package aoc2023
|
|
|
|
import println
|
|
import readInput
|
|
|
|
/*
|
|
--- Day 1: Trebuchet?! ---
|
|
https://adventofcode.com/2023/day/1
|
|
*/
|
|
fun main() {
|
|
|
|
val inlineTestInput = """
|
|
1abc2
|
|
pqr3stu8vwx
|
|
a1b2c3d4e5f
|
|
treb7uchet
|
|
"""
|
|
val inlineTestInput2 = """
|
|
two1nine
|
|
eightwothree
|
|
abcone2threexyz
|
|
xtwone3four
|
|
4nineeightseven2
|
|
zoneight234
|
|
7pqrstsixteen
|
|
"""
|
|
|
|
fun part1(input: List<String>): Int {
|
|
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 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 -1
|
|
}
|
|
|
|
fun part2(input: List<String>): Int {
|
|
return input.sumOf { findFirst(it, digitStrings) * 10 + findFirst(it.reversed(), digitStringsRev) }
|
|
}
|
|
|
|
// test if implementation meets criteria from the description, like:
|
|
val testInput = inlineTestInput.trim().reader().readLines()
|
|
val testInput2 = inlineTestInput2.trim().reader().readLines()
|
|
//val testInput = readInput("aoc2023/Day01_test")
|
|
println("Part 1 Test: " + part1(testInput))
|
|
println("Part 2 Test: " + part2(testInput2))
|
|
check(part1(testInput) == 142)
|
|
check(part2(testInput2) == 281)
|
|
|
|
val input = readInput("aoc2023/Day01")
|
|
part1(input).println()
|
|
part2(input).println()
|
|
}
|