generated from mariotacke/template-advent-of-code
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhaversacks2.js
31 lines (22 loc) · 782 Bytes
/
haversacks2.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
module.exports = (input) => {
const rules = input.split('\n').reduce((rules, line) => {
const [, color, otherColors] = /(\w+ \w+) bags contain (.*)\./.exec(line);
const compatibleWith = otherColors !== 'no other bags'
? otherColors.split(', ').map((other) => {
const [, units, color] = /(\d+) (\w+ \w+) bags?/.exec(other);
return { units: parseInt(units), color };
})
: [];
rules.set(color, []);
compatibleWith.forEach((otherColor) => rules.get(color).push(otherColor));
return rules;
}, new Map());
const traverse = (bag) => {
let total = 0;
for (const { color, units } of rules.get(bag)) {
total += units + units * traverse(color);
}
return total;
};
return traverse('shiny gold');
};