-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay01.kt
51 lines (44 loc) · 1.42 KB
/
Day01.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package adventofcode2023
import java.io.File
object Day01 {
fun part1(inputs: List<String>) {
println(inputs.sumOf { line ->
val digits = line.filter { char -> char.isDigit() }
digits.first().digitToInt() * 10 + digits.last().digitToInt()
})
}
fun part2(inputs: List<String>) {
val digits = setOf(
Pair("one", '1'),
Pair("two", '2'),
Pair("three", '3'),
Pair("four", '4'),
Pair("five", '5'),
Pair("six", '6'),
Pair("seven", '7'),
Pair("eight", '8'),
Pair("nine", '9')
)
fun findDigit(line: String, indices: IntProgression = line.indices): Int {
for (i in indices) {
for (digit in digits) {
if ((line.length >= i + digit.first.length
&& line.substring(i, i + digit.first.length) == digit.first)
|| line[i] == digit.second
) {
return digit.second.digitToInt()
}
}
}
return 0
}
println(inputs.sumOf { line ->
findDigit(line) * 10 + findDigit(line, line.indices.reversed())
})
}
}
fun main() {
val inputs = File("resources/adventofcode2023/Day01.txt").readLines()
Day01.part1(inputs)
Day01.part2(inputs)
}