-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path24a.js
81 lines (61 loc) · 1.74 KB
/
24a.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
import {readInput} from "./lib.js";
const input = readInput(24);
const brk = input.findIndex(line => line === "");
const wires = new Map(input.slice(0, brk).map((line) => {
const [wire, value ] = line.split(': ')
return [wire, value === '1'];
}));
const gateFns = {
AND(gate) {
const {first, second, target} = gate;
wires.set(target, wires.get(first) && wires.get(second));
},
OR(gate) {
const {first, second, target} = gate;
wires.set(target, wires.get(first) || wires.get(second));
},
XOR(gate) {
const {first, second, target} = gate;
wires.set(target, wires.get(first) !== wires.get(second));
}
}
const gates = input.slice(brk + 1).map((line) => {
const [, first, type, second, target] = /(\w+) (\w+) (\w+) -> (\w+)/.exec(line);
return {
first,
type,
second,
target,
}
});
const seen = new Set();
const queue = [...gates];
while (queue.length) {
const gate = queue.shift();
if (seen.has(gate)) {
continue;
}
const { first, second, target } = gate;
if (wires.has(first) && wires.has(second)) {
seen.add(gate);
gateFns[gate.type](gate);
const targets = gates.filter(({first, second}) => first === target || second === target);
queue.unshift(...targets);
}
}
console.log(
[...wires.entries()]
// .filter(([wire]) => wire.startsWith('z'))
.map(([wire, value]) => `${wire}: ${value ? 1 : 0}`)
.sort()
.join('\n')
);
console.log(
parseInt(
[...wires.entries()]
.filter(([wire]) => wire.startsWith('z'))
.sort(([a], [b]) => b.localeCompare(a))
.map(([, value]) => value ? 1 : 0)
.join('')
, 2)
);