-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpacket-scanner2.js
81 lines (64 loc) · 1.59 KB
/
packet-scanner2.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const packetScanner = (input) => {
const layers = input
.split('\n')
.map((layer) => {
const [depth, range] = layer
.trim()
.split(': ')
.map((x) => parseInt(x));
return {
depth,
range,
};
});
const tick = (array, direction = 1) => {
array.forEach((layer) => {
if (layer) {
layer.position += layer.direction;
if (layer.position === layer.range - 1 || layer.position === 0) {
layer.direction *= -1 * direction;
}
}
});
};
const firewallDepth = layers[layers.length - 1].depth;
let firewall = new Array(firewallDepth).fill(null);
for (let i = 0; i < firewallDepth; i++) {
if (layers[i]) {
const { depth, range } = layers[i];
firewall[depth] = {
depth,
range,
position: 0,
direction: 1,
};
}
}
const packet = {
canPassSafely: false,
hasBeenCaught: false,
delay: 0,
position: 0,
};
let firewallSnapshot = JSON.stringify(firewall);
while (!packet.canPassSafely) {
for (let i = 0; i <= firewallDepth; i++) {
const layer = firewall[i];
packet.position = i;
if (layer && layer.position === 0) {
packet.hasBeenCaught = true;
}
tick(firewall);
}
if (!packet.hasBeenCaught) {
packet.canPassSafely = true;
}
firewall = JSON.parse(firewallSnapshot);
tick(firewall);
firewallSnapshot = JSON.stringify(firewall);
packet.delay += 1;
packet.hasBeenCaught = false;
}
return packet.delay - 1;
};
module.exports = packetScanner;