|
1 | 1 | package adventofcode2023
|
2 | 2 |
|
3 | 3 | import java.io.File
|
| 4 | +import java.util.PriorityQueue |
4 | 5 |
|
5 | 6 | object Day22 {
|
6 | 7 | private const val EMPTY = -1
|
7 | 8 | private const val FLOOR = 0
|
8 | 9 |
|
9 |
| -// private val bricks = ("1,0,1~1,2,1\n" + |
10 |
| -// "0,0,2~2,0,2\n" + |
11 |
| -// "0,2,3~2,2,3\n" + |
12 |
| -// "0,0,4~0,2,4\n" + |
13 |
| -// "2,0,5~2,2,5\n" + |
14 |
| -// "0,1,6~2,1,6\n" + |
15 |
| -// "1,1,8~1,1,9").split("\n") |
16 | 10 | private val bricks = File("resources/adventofcode2023/Day22.txt")
|
17 | 11 | .readLines()
|
18 | 12 | .withIndex()
|
@@ -77,7 +71,7 @@ object Day22 {
|
77 | 71 | fun numberOfSupporting(): Int =
|
78 | 72 | verticalNeighborsIds(false).size
|
79 | 73 |
|
80 |
| - fun supports(): List<Brick> = |
| 74 | + fun supportedBricks(): List<Brick> = |
81 | 75 | verticalNeighborsIds(true).map { bricks[it - 1] }
|
82 | 76 |
|
83 | 77 | fun fall(): Boolean {
|
@@ -106,30 +100,24 @@ object Day22 {
|
106 | 100 |
|
107 | 101 | private fun numberOfSafeToDisintegrate(): Int =
|
108 | 102 | bricks.count { brick ->
|
109 |
| - brick.supports().all { it.numberOfSupporting() > 1 } |
| 103 | + brick.supportedBricks().all { it.numberOfSupporting() > 1 } |
110 | 104 | }
|
111 | 105 |
|
112 |
| - // This function doesn't work for the bigger input somehow... |
113 |
| - // It works for the example input from the question |
114 | 106 | private fun numberOfBrickThatWouldFall(brick: Brick): Int {
|
115 |
| - var currentBricks = brick.supports() |
116 |
| - var lastIds = listOf(brick.id) |
| 107 | + val currentBricks = PriorityQueue<Brick> { brick1, brick2 -> brick1.end.z - brick2.end.z } |
| 108 | + val fallenIds = mutableListOf(brick.id) |
117 | 109 | var fallenCount = 0
|
118 | 110 |
|
| 111 | + currentBricks.addAll(brick.supportedBricks()) |
| 112 | + |
119 | 113 | while (currentBricks.isNotEmpty()) {
|
120 |
| - val nextBricks = mutableListOf<Brick>() |
121 |
| - val currentIds = mutableListOf<Int>() |
122 |
| - |
123 |
| - currentBricks.forEach { current -> |
124 |
| - if (current.verticalNeighborsIds(false).all { lastIds.contains(it) }) { |
125 |
| - nextBricks.addAll(current.supports().filterNot { nextBricks.contains(it) }) |
126 |
| - currentIds.add(current.id) |
127 |
| - fallenCount++ |
128 |
| - } |
129 |
| - } |
| 114 | + val current = currentBricks.remove() |
130 | 115 |
|
131 |
| - currentBricks = nextBricks |
132 |
| - lastIds = currentIds |
| 116 | + if (current.verticalNeighborsIds(false).all { fallenIds.contains(it) }) { |
| 117 | + if (!fallenIds.contains(current.id)) fallenIds.add(current.id) |
| 118 | + currentBricks.addAll(current.supportedBricks().filterNot { currentBricks.contains(it) }) |
| 119 | + fallenCount++ |
| 120 | + } |
133 | 121 | }
|
134 | 122 |
|
135 | 123 | println("${brick.id}: $fallenCount")
|
|
0 commit comments