From 946048f3f190ce3f1aa58a741c85225a2d54fcca Mon Sep 17 00:00:00 2001 From: Chris Hodges Date: Fri, 22 Dec 2023 10:28:32 +0100 Subject: [PATCH] Day 22 Part 2. Change-Id: I60222815834fd3180a842d3c0f1f70bc9ed2ed67 --- src/aoc2023/Day22.kt | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/src/aoc2023/Day22.kt b/src/aoc2023/Day22.kt index f3f4aa6..5acee1f 100644 --- a/src/aoc2023/Day22.kt +++ b/src/aoc2023/Day22.kt @@ -152,7 +152,8 @@ fun main() { fun parts(input: List, width: Int, height: Int): Pair { val bricks = input.mapIndexed { id, it -> - val (x1, y1, z1, x2, y2, z2) = "(\\d+),(\\d+),(\\d+)~(\\d+),(\\d+),(\\d+)".toRegex().matchEntire(it)?.destructured!! + val (x1, y1, z1, x2, y2, z2) = "(\\d+),(\\d+),(\\d+)~(\\d+),(\\d+),(\\d+)".toRegex() + .matchEntire(it)?.destructured!! Brick(id, x1.toInt(), y1.toInt(), z1.toInt(), x2.toInt(), y2.toInt(), z2.toInt()) } .sortedBy { it.z2 } @@ -179,16 +180,23 @@ fun main() { brickTopZ[y * width + x] = flatTopZ + b.h() } } - //brickTopZ.asSequence().chunked(width).joinToString("\n") { it.joinToString(" ") { String.format("%3d", it) } }.println() - //println() } - val fallingSet = HashSet() - //println(bricks.map { "%c: %d".format(('A' + it.id), it.onTopBricks.size) }) val disBricks = bricks.filterNot { it.onTopBricks.all { it.uponBricks.size != 1 } } val safeBricks = bricks.size - disBricks.size - println(disBricks) - val fallingBricks = disBricks.map { it.onTopBricks.filter { it.uponBricks.size < 2 }.size }.sum() - return safeBricks to fallingBricks + var sum = 0 + for (brick in disBricks) { + val fallingSet = HashSet() + val removeQueue = ArrayDeque() + fallingSet.add(brick) + removeQueue.add(brick) + while (removeQueue.isNotEmpty()) { + val falling = removeQueue.removeFirst() + fallingSet.add(falling) + removeQueue.addAll(falling.onTopBricks.filter { it.uponBricks.subtract(fallingSet).isEmpty() }) + } + sum += fallingSet.size - 1 + } + return safeBricks to sum } // test if implementation meets criteria from the description, like: