-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay10.kt
67 lines (53 loc) · 1.89 KB
/
Day10.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package aoc.years.year2024
import aoc.Day
@Year2024
class Day10 : Day() {
override fun solvePart1(input: List<String>): Any {
return TrailMap.of(input).getTrailheadScore()
}
override fun solvePart2(input: List<String>): Any {
return TrailMap.of(input).getTrailheadRating()
}
}
private class TrailMap(val map: List<List<Int>>) {
companion object {
fun of(input: List<String>): TrailMap {
val map = input.map { it.map(Char::digitToInt) }
return TrailMap(map)
}
}
fun getTrailheadScore(): Int {
return getTrailheads().sumOf { it.getTrailends().size }
}
private fun Pair<Int, Int>.getTrailends(): Set<Pair<Int, Int>> {
if (map[this.first][this.second] == 9) {
return setOf(this)
}
return this.getSurroundingPath().map { it.getTrailends() }.flatten().toSet()
}
fun getTrailheadRating(): Int {
return getTrailheads().sumOf { it.getTrailPaths() }
}
private fun Pair<Int, Int>.getTrailPaths(): Int {
if (map[this.first][this.second] == 9) {
return 1
}
return this.getSurroundingPath().sumOf { it.getTrailPaths() }
}
private fun getTrailheads(): List<Pair<Int, Int>> {
val trailheads = mutableListOf<Pair<Int, Int>>()
for (x in map.indices) {
for (y in map[x].indices) {
if (map[x][y] == 0) {
trailheads.add(Pair(x, y))
}
}
}
return trailheads
}
private fun Pair<Int, Int>.getSurroundingPath(): List<Pair<Int, Int>> {
return listOf(Pair(first + 1, second), Pair(first - 1, second), Pair(first, second + 1), Pair(first, second - 1))
.filter { it.first in map.indices && it.second in map[it.first].indices }
.filter { map[it.first][it.second] == map[first][second] + 1 }
}
}