import java.io.File import kotlin.text.Regex fun main() { part1() part2() } fun part1() { val input = File("input") val numbers: List = input.useLines { it.map { getPairsOfDigits(it) }.map { digitsToInt(it) }.toList() } println(numbers.sum()) } fun part2() { val input = File("input") val numbers: List = input.useLines { it.map { getPairsOfDigitsAndNames(it) }.map { digitsToInt(it) }.toList() } println(numbers.sum()) } fun getPairsOfDigits(line: String): Pair { return line.fold(Pair(null, null)) { acc, next -> try { val digit = next.digitToInt() if (acc.first == null) { Pair(digit, null) } else { Pair(acc.first, digit) } } catch (nfe: IllegalArgumentException) { acc } } } fun getPairsOfDigitsAndNames(line: String): Pair { val matchValues = Regex("one|two|three|four|five|six|seven|eight|nine|0|1|2|3|4|5|6|7|8|9") val digits = matchValues.findAll(line) val matchToInt = { it: String -> when (it) { "one" -> 1 "two" -> 2 "three" -> 3 "four" -> 4 "five" -> 5 "six" -> 6 "seven" -> 7 "eight" -> 8 "nine" -> 9 "0" -> 0 "1" -> 1 "2" -> 2 "3" -> 3 "4" -> 4 "5" -> 5 "6" -> 6 "7" -> 7 "8" -> 8 "9" -> 9 else -> throw IllegalArgumentException("Illegal character: '${it}'") } } val first = matchToInt(digits.first().value) val last = matchToInt(digits.last().value) println("${line}: ${first}, ${last}") return Pair(first, last) } fun digitsToInt(digits: Pair): Int { return when { digits.first == null -> throw Exception("no digit found on a line") digits.second == null -> digits.first as Int * 10 + digits.first as Int else -> digits.first as Int * 10 + digits.second as Int } }