-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
65 lines (53 loc) · 1.5 KB
/
index.js
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
import '../lib.js'
const lines = readLines()
const cubes = lines.map(matchPositiveNumbers)
const faces = new Set()
function addFace(x, y, z) {
const key = x * 10000 + y * 100 + z
// toggles key (2 occurrences = not in contact with air)
faces.delete(key) || faces.add(key)
}
function addCubeFaces(x, y, z) {
addFace(x - 0.5, y, z)
addFace(x + 0.5, y, z)
addFace(x, y - 0.5, z)
addFace(x, y + 0.5, z)
addFace(x, y, z - 0.5)
addFace(x, y, z + 0.5)
}
cubes.forEach(([x, y, z]) => addCubeFaces(x, y, z))
logStar1(faces.size)
// Part 2. Put the lava droplet into a larger cube (24*24*24) and
// 3D flood fill this container
faces.clear()
const cubeKey = (x, y, z) => (x << 16) | (y << 8) | z
const cubeSet = new Set(cubes.map(([x, y, z]) => cubeKey(x + 1, y + 1, z + 1)))
const W = 24
function floodFill() {
// start from the (0,0,0) corner, whith is water
const queue = [0]
const visited = new Set(queue)
function add(pos) {
if (!visited.has(pos)) {
visited.add(pos)
queue.push(pos)
}
}
while (queue.length) {
const key = queue.shift()
if (cubeSet.has(key)) continue
const x = key >> 16
const y = (key >> 8) & 0xff
const z = key & 0xff
addCubeFaces(x, y, z)
if (x > 0) add(key - 0x10000)
if (x < W - 1) add(key + 0x10000)
if (y > 0) add(key - 0x100)
if (y < W - 1) add(key + 0x100)
if (z > 0) add(key - 1)
if (z < W - 1) add(key + 1)
}
}
floodFill()
const containerOusideFaces = 6 * W ** 2
logStar2(faces.size - containerOusideFaces)