/
Part1.kt
51 lines (41 loc) · 1.31 KB
/
Part1.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
import java.io.File
typealias Pos = Pair<Int, Int>
fun findNumbers(input: List<String>, includePositions: Set<Pos>): List<Int> {
val regex = "\\d+".toRegex()
val results = mutableListOf<Int>()
for ((y, row) in input.withIndex()) {
var matchResult: MatchResult? = regex.find(row)
while (matchResult != null) {
val number = matchResult.value
for (x in matchResult.range) {
if (includePositions.contains(Pair(x, y))) {
results.add(number.toInt())
break
}
}
matchResult = matchResult.next()
}
}
return results
}
fun findNonDigitPositions(input: List<String>): Set<Pos> {
val results = mutableSetOf<Pos>()
for ((y, row) in input.withIndex()) {
for ((x, character) in row.withIndex()) {
if (character !in '0'..'9' && character != '.') {
for (i in -1..1) {
for (j in -1..1) {
results.add(Pair(x + i, y + j))
}
}
}
}
}
return results
}
fun main() {
val input = File("input.txt").readText()
val lines = input.lines()
val covered = findNonDigitPositions(lines)
println(findNumbers(lines, covered).sum())
}