Complete day 1
Note: For some reason my input results in part 2 being exactly 10 less than it should be, I suspect this is a bug in the input data?
This commit is contained in:
commit
cedf1b8c0e
5 changed files with 1137 additions and 0 deletions
84
day1/day1.kt
Normal file
84
day1/day1.kt
Normal file
|
@ -0,0 +1,84 @@
|
|||
import java.io.File
|
||||
import kotlin.text.Regex
|
||||
|
||||
fun main() {
|
||||
part1()
|
||||
part2()
|
||||
}
|
||||
|
||||
fun part1() {
|
||||
val input = File("input")
|
||||
val numbers: List<Int> =
|
||||
input.useLines { it.map { getPairsOfDigits(it) }.map { digitsToInt(it) }.toList() }
|
||||
|
||||
println(numbers.sum())
|
||||
}
|
||||
|
||||
fun part2() {
|
||||
val input = File("input")
|
||||
val numbers: List<Int> =
|
||||
input.useLines {
|
||||
it.map { getPairsOfDigitsAndNames(it) }.map { digitsToInt(it) }.toList()
|
||||
}
|
||||
println(numbers.sum())
|
||||
}
|
||||
|
||||
fun getPairsOfDigits(line: String): Pair<Int?, Int?> {
|
||||
return line.fold(Pair<Int?, Int?>(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<Int?, Int?> {
|
||||
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?, Int?>): 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
|
||||
}
|
||||
}
|
1000
day1/input
Normal file
1000
day1/input
Normal file
File diff suppressed because it is too large
Load diff
7
day1/test
Normal file
7
day1/test
Normal file
|
@ -0,0 +1,7 @@
|
|||
two1nine
|
||||
eightwothree
|
||||
abcone2threexyz
|
||||
xtwone3four
|
||||
4nineeightseven2
|
||||
zoneight234
|
||||
7pqrstsixteen
|
Loading…
Add table
Add a link
Reference in a new issue