Skip to content

Commit 0bd5f79

Browse files
committed
Day 22 - Fix for cascade method
1 parent eb99389 commit 0bd5f79

File tree

2 files changed

+10
-46
lines changed

2 files changed

+10
-46
lines changed

days/22-2/main.go

Lines changed: 9 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -135,53 +135,18 @@ func main() {
135135

136136
total := 0
137137
for i := 0; i < len(bricks); i++ {
138-
newBricks := append([]brick{}, bricks[:i]...)
139-
newBricks = append(newBricks, bricks[i+1:]...)
140-
count := restack(newBricks)
141-
total += count
142-
}
143-
144-
fmt.Println(total)
145-
}
146-
147-
func restack(bricks []brick) int {
148-
moved := make(map[int]struct{})
149-
for i := 0; i < len(bricks); i++ {
150-
if bricks[i].start.z == 1 {
151-
continue
152-
}
138+
removed := []int{i}
139+
closed := []int{}
140+
count := 0
141+
cascade(bricks, i, supportedBy, &removed, &closed, &count)
153142

154-
// check if the brick can move down
155-
for {
156-
testZ := bricks[i].start.z - 1
157-
canMove := true
158-
for j := 0; j < i; j++ {
159-
if bricks[j].end.z >= testZ {
160-
if intersect(bricks[i], bricks[j]) {
161-
canMove = false
162-
}
163-
}
164-
}
165-
166-
if !canMove {
167-
break
168-
}
169-
170-
bricks[i].start.z--
171-
bricks[i].end.z--
172-
173-
moved[i] = struct{}{}
174-
175-
if bricks[i].start.z == 1 {
176-
break
177-
}
178-
}
143+
total += (count - 1)
179144
}
180145

181-
return len(moved)
146+
fmt.Println(total)
182147
}
183148

184-
func cascade(bricks []brick, b int, supportedBy map[int][]int, removed []int, closed *[]int, count *int) {
149+
func cascade(bricks []brick, b int, supportedBy map[int][]int, removed *[]int, closed *[]int, count *int) {
185150
if slices.Contains(*closed, b) {
186151
return
187152
}
@@ -193,20 +158,19 @@ func cascade(bricks []brick, b int, supportedBy map[int][]int, removed []int, cl
193158
// check if all of the blocks support has been removed
194159
allRemoved := true
195160
for _, by := range supportedBy[support] {
196-
if !slices.Contains(removed, by) {
161+
if !slices.Contains(*removed, by) {
197162
allRemoved = false
198163
break
199164
}
200165
}
201166

202167
if allRemoved {
203-
removed = append(removed, support)
168+
*removed = append(*removed, support)
204169
cascadeTo = append(cascadeTo, support)
205170
}
206171
}
207172

208173
*closed = append(*closed, b)
209-
210174
for _, c := range cascadeTo {
211175
cascade(bricks, c, supportedBy, removed, closed, count)
212176
}

days_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ var expectations = map[string]string{
4848
"20-2": "232774988886497",
4949
"21-1": "3699",
5050
"22-1": "457",
51-
"22-2": "79122", // TODO: Make this faster using something like cascade solution
51+
"22-2": "79122",
5252
}
5353

5454
func TestDays(t *testing.T) {

0 commit comments

Comments
 (0)