-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathy23day3part2.kt
More file actions
36 lines (36 loc) · 1.43 KB
/
Copy pathy23day3part2.kt
File metadata and controls
36 lines (36 loc) · 1.43 KB
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
fun main() {
data class Point(val x: Int, val y: Int)
generateSequence { readlnOrNull() }.toList().let { rows ->
val gears = mutableMapOf<Point, MutableList<Int>>()
rows.forEachIndexed { i, row ->
var digitsCount = 0
val adjacentGears = mutableSetOf<Point>()
fun adj(i: Int, j: Int) {
if (i in 0..<rows.size && j in 0..<rows[i].length && rows[i][j] != '.') {
adjacentGears += Point(i, j)
}
}
row.forEachIndexed { j, symbol ->
if (symbol.isDigit()) {
if (digitsCount == 0) {
adj(i, j-1); adj(i-1, j-1); adj(i+1,j-1)
}
adj(i-1, j); adj(i+1, j)
++digitsCount
if (j == row.length-1 || !row[j+1].isDigit()) {
adj(i, j+1); adj(i-1, j+1); adj(i+1, j+1)
val number = row.substring(j-digitsCount+1, j+1).toInt()
adjacentGears.forEach {
gears.getOrPut(it) { mutableListOf() } += number
}
adjacentGears.clear()
digitsCount = 0
}
}
}
}
gears.values.sumOf { numbers ->
numbers.let { if (it.size == 2) it[0] * it[1] else 0 }
}.let(::println)
}
}