-
Notifications
You must be signed in to change notification settings - Fork 0
/
day10b.js
34 lines (27 loc) · 1003 Bytes
/
day10b.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
const fs = require('fs');
const data = fs.readFileSync('input10.txt', { encoding: 'utf8' });
const input = data.split(/\r?\n/).map(n => +n).sort((a, b) => a - b);
const jolts = [0, ...input, input[input.length - 1] + 3];
const permutations = adapters => {
const mutabor = adapters.slice(1, adapters.length - 1);
const power = 1 << mutabor.length;
const first = adapters[0];
const last = adapters[adapters.length - 1];
let variants = 0;
for (let i = 0; i < power; ++i) {
const chain = [first, ...mutabor.filter((v, index) => i & (1 << index)), last];
variants += chain.reduce((acc, n, i, v) => (i && n - v[i - 1] > 3) ? 0 : acc, 1);
}
return variants;
}
const chain = [];
let variants = 1;
for (let i = 0, l = jolts.length; i < l; ++i) {
const jolt = jolts[i];
if (jolt - jolts[i - 1] === 3) { // lets process the subchain for variations
variants *= chain.length > 2 ? permutations(chain) : 1;
chain.length = 0;
}
chain.push(jolt);
}
console.log(variants);