-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbots2.js
91 lines (74 loc) · 2.18 KB
/
bots2.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
82
83
84
85
86
87
88
89
90
91
class Bot {
constructor (factory) {
this.chips = [];
this._factory = factory;
}
add (chip) {
this.chips = [...this.chips, chip].sort((a, b) => a - b);
}
distribute () {
const [low, high] = this.chips;
if (this._lowTo.match(/output/g)) {
this._factory.outputs[this._lowTo] = low;
} else {
this._factory.bots[this._lowTo].add(low);
}
if (this._highTo.match(/output/g)) {
this._factory.outputs[this._highTo] = high;
} else {
this._factory.bots[this._highTo].add(high);
}
this.chips = [];
}
setBehavior (lowTo, highTo) {
this._lowTo = lowTo;
this._highTo = highTo;
}
}
const bots = (input) => {
const factory = {
bots: {},
outputs: {},
};
const instructions = input
.split('\n')
.map((x) => x.trim());
// determine unique bots
[...new Set(instructions
.filter((x) => x.includes('bot'))
.map((x) => x.match(/bot \d+/g))
.reduce((a, b) => a.concat(b), []))]
.forEach((x) => factory.bots[x] = new Bot(factory));
// determine unique outputs
[...new Set(instructions
.filter((x) => x.includes('output'))
.map((x) => x.match(/output \d+/g))
.reduce((a, b) => a.concat(b), []))]
.forEach((x) => factory.outputs[x] = null);
// seed bots with starting values
instructions
.filter((x) => x.match(/value \d+ goes to bot \d+/))
.forEach((x) => {
const [, value, bot] = x.match(/value (\d+) goes to (bot \d+)/);
factory.bots[bot].add(+value);
});
// determine bot behavior
instructions
.filter((x) => x.match(/bot \d+ gives low to \w+ \d+ and high to \w+ \d+/))
.forEach((x) => {
const [, bot, lowTo, highTo] = x.match(/(bot \d+) gives low to (\w+ \d+) and high to (\w+ \d+)/);
factory.bots[bot].setBehavior(lowTo, highTo);
});
// simulate factory
while (Object.values(factory.outputs).some((x) => x === null)) {
Object.keys(factory.bots).forEach((bot) => {
if (factory.bots[bot].chips.length === 2) {
factory.bots[bot].distribute();
}
});
}
return factory.outputs['output 0'] *
factory.outputs['output 1'] *
factory.outputs['output 2'];
};
module.exports = bots;