@@ -8,34 +8,76 @@ object Day14 {
8
8
9
9
private val inputs = File (" resources/adventofcode2023/Day14.txt" ).readLines()
10
10
11
- private fun rollAllNorth (): List <String > {
12
- val rolledInputs = inputs.map { it.toMutableList() }
13
-
14
- for (y in rolledInputs.indices) {
15
- for (x in rolledInputs[y].indices) {
16
- if (rolledInputs[y][x] == ROUNDED_ROCK ) {
17
- var currentY = y
18
-
19
- while (currentY > 0 && rolledInputs[currentY - 1 ][x] == EMPTY ) {
20
- rolledInputs[currentY][x] = EMPTY
21
- currentY--
22
- rolledInputs[currentY][x] = ROUNDED_ROCK
11
+ private fun rollAll (rocks : List <String >, direction : Pair <Int , Int >): List <String > {
12
+ val rolled = rocks.map { it.toMutableList() }
13
+
14
+ val yIndices = if (direction.second < 0 ) rolled.indices else rolled.indices.reversed()
15
+ val xIndices = if (direction.first < 0 ) rolled[0 ].indices else rolled[0 ].indices.reversed()
16
+
17
+ for (y in yIndices) {
18
+ for (x in xIndices) {
19
+ if (rolled[y][x] == ROUNDED_ROCK ) {
20
+ var nextX = x + direction.first
21
+ var nextY = y + direction.second
22
+
23
+ while (
24
+ nextY >= 0 && nextX >= 0 && nextY < rolled.size && nextX < rolled[nextY].size &&
25
+ rolled[nextY][nextX] == EMPTY
26
+ ) {
27
+ rolled[nextY - direction.second][nextX - direction.first] = EMPTY
28
+ rolled[nextY][nextX] = ROUNDED_ROCK
29
+
30
+ nextX + = direction.first
31
+ nextY + = direction.second
23
32
}
24
33
}
25
34
}
26
35
}
27
36
28
- return rolledInputs.map { it.joinToString(separator = " " ) }
37
+ return rolled.map { it.joinToString(separator = " " ) }
38
+ }
39
+
40
+ private fun spinCycle (rocks : List <String >): List <String > =
41
+ rollAll(rollAll(rollAll(rollAll(rocks, Pair (0 , - 1 )), Pair (- 1 , 0 )), Pair (0 , 1 )), Pair (1 , 0 ))
42
+
43
+ private fun runSpinCycles (rocks : List <String >, cycles : Int ): List <String > {
44
+ var current = rocks
45
+ val history = mutableListOf<List <String >>()
46
+ var cycle = 0
47
+
48
+ while (cycle < cycles) {
49
+ current = spinCycle(current)
50
+
51
+ val lastAppearedIndex = history.indexOf(current)
52
+ if (lastAppearedIndex > - 1 ) {
53
+ val toAdd = cycle - lastAppearedIndex
54
+ cycle + = ((cycles - cycle) / toAdd) * toAdd
55
+ }
56
+
57
+ history.add(current)
58
+ cycle++
59
+ }
60
+
61
+ return current
29
62
}
30
63
31
- fun part1 () =
32
- println (rollAllNorth() .withIndex().sumOf { line ->
64
+ private fun calculateNorthLoad ( rocks : List < String >): Int =
65
+ rocks .withIndex().sumOf { line ->
33
66
line.value.sumOf {
34
- if (it == ROUNDED_ROCK ) inputs .size - line.index else 0
67
+ if (it == ROUNDED_ROCK ) rocks .size - line.index else 0
35
68
}
36
- })
69
+ }
70
+
71
+ fun part1 () = println (
72
+ calculateNorthLoad(rollAll(inputs, Pair (0 , - 1 )))
73
+ )
74
+
75
+ fun part2 () = println (
76
+ calculateNorthLoad(runSpinCycles(inputs, 1000000000 ))
77
+ )
37
78
}
38
79
39
80
fun main () {
40
81
Day14 .part1()
82
+ Day14 .part2()
41
83
}
0 commit comments