-
Notifications
You must be signed in to change notification settings - Fork 0
/
day1.kt
48 lines (42 loc) · 1.29 KB
/
day1.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
import java.io.File
fun main() {
val lineList = mutableListOf<String>()
File("src/main/resources/day1.txt").useLines { lines -> lines.forEach { lineList.add(it)} }
var sum = 0
var sum2 = 0
lineList.forEach {
sum += firstAndLastNumbers(it)
sum2 += firstAndLastNumbers(replaceNumberStringsWithIntegers(it))
}
println("[Part 1 Solution] Sum of all numbers: $sum")
println("[Part 2 Solution] Sum of all numbers: $sum2")
}
fun firstAndLastNumbers(line: String): Int {
val lineNumbers = mutableListOf<Int>()
for (i in line) {
if (i.code in 48..57) {
lineNumbers.add(i.code - 48)
break
}
}
val reversed = line.reversed()
for (i in reversed) {
if (i.code in 48..57) {
lineNumbers.add(i.code - 48)
break
}
}
return lineNumbers[0] * 10 + lineNumbers[1]
}
fun replaceNumberStringsWithIntegers(line: String): String {
val numberMap = mapOf(
"one" to "o1e", "two" to "t2o", "three" to "t3e",
"four" to "4", "five" to "5e", "six" to "6",
"seven" to "7n", "eight" to "e8t", "nine" to "9e"
)
var resultLine = line
numberMap.forEach {(key, value) ->
resultLine = resultLine.replace(key, value)
}
return resultLine
}