-
Notifications
You must be signed in to change notification settings - Fork 0
/
b.test.ts
92 lines (68 loc) · 2.56 KB
/
b.test.ts
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { expect, test } from "bun:test";
type Brick = [startX: number, startY: number, startZ: number, endX: number, endY: number, endZ: number];
function byAscZ([, , sz1, , , ez1]: Brick, [, , sz2, , , ez2]: Brick) {
return Math.min(sz1, ez1) - Math.min(sz2, ez2);
}
function overlaps([sx1, sy1, , ex1, ey1]: Brick, [sx2, sy2, , ex2, ey2]: Brick) {
return Math.max(sx1, sx2) <= Math.min(ex1, ex2) && Math.max(sy1, sy2) <= Math.min(ey1, ey2);
}
function solution(input: string) {
const bricks = input.split("\n").map((line) => {
return line.replace("~", ",").split(",").map(Number) as Brick;
});
bricks.sort(byAscZ);
for (const [index, brick] of bricks.entries()) {
let maxZ = 1;
for (const check of bricks.slice(0, index)) {
if (overlaps(check, brick)) {
maxZ = Math.max(maxZ, check[5] + 1);
}
}
brick[5] -= brick[2] - maxZ;
brick[2] = maxZ;
}
bricks.sort(byAscZ);
const brickSupportedBy = Array.from({ length: bricks.length }, () => new Set<number>());
const brickSupports = Array.from({ length: bricks.length }, () => new Set<number>());
for (const [i, upper] of bricks.entries()) {
for (const [j, lower] of bricks.slice(0, i).entries()) {
if (overlaps(lower, upper) && upper[2] === lower[5] + 1) {
brickSupportedBy[j].add(i);
brickSupports[i].add(j);
}
}
}
let ans = 0;
for (const i of bricks.keys()) {
const queue = [...brickSupportedBy[i]].filter((j) => brickSupports[j].size === 1);
const falling = new Set(queue);
falling.add(i);
while (queue.length) {
const j = queue.shift();
if (!j) throw new Error("Unexpected");
for (const k of brickSupportedBy[j]) {
if (falling.has(k)) continue;
if ([...brickSupports[k]].every((l) => falling.has(l))) {
queue.push(k);
falling.add(k);
}
}
}
ans += falling.size - 1;
}
return ans;
}
test("example", async () => {
const file = Bun.file(`${import.meta.dir}/example.txt`);
const input = await file.text();
const actual = solution(input);
const expected = 7;
expect(actual).toBe(expected);
});
test("puzzle input", async () => {
const file = Bun.file(`${import.meta.dir}/input.txt`);
const input = await file.text();
const actual = solution(input);
const expected = 63166;
expect(actual).toBe(expected);
});