Published
Edited
Dec 9, 2020
Insert cell
Insert cell
Insert cell
class Bag {
constructor( color ) {
this.color = color;
this.rules = [];
}
contains( qty, color ) {
this.rules.push( [ qty, color ] );
}
}
Insert cell
parseRule = rule => {
const [outerColor, innerRules] = rule.split(' bags contain ');
const bag = new Bag(outerColor);
const matches = innerRules.matchAll(/(\d) (\w+ \w+) bags?/g);
for (const match of matches) {
bag.contains(parseInt(match[1]), match[2]);
}
return bag;
}
Insert cell
function recursiveBagSearch(bagsToContainers, memoSet, target) {
const containers = bagsToContainers.get(target);
if (!containers) return;
containers.forEach(color => {
if (!memoSet.has(color)) {
memoSet.add(color);
recursiveBagSearch(bagsToContainers, memoSet, color);
}
});
}
Insert cell
findContainingBags = (input, target) => {
const bags = input.split('\n').map(parseRule);
const bagsContainedBy = bags.reduce((memo, bag) => {
bag.rules.forEach(([_, innerColor]) => {
if (memo.has(innerColor)) {
memo.get(innerColor).push(bag.color);
} else {
memo.set(innerColor, [bag.color]);
}
});
return memo;
}, new Map());

// return bagsContainedBy;

const bagSet = new Set();
recursiveBagSearch(bagsContainedBy, bagSet, target);
return bagSet;
}
Insert cell
findContainingBags(testInput, 'shiny gold')
Insert cell
Insert cell
Insert cell
findContainingBags(input, 'shiny gold')
Insert cell
Insert cell
function recusiveChildSearch(bagsByColor, color) {
const bag = bagsByColor.get(color);
return bag.rules.reduce((count, [qty, childColor]) => {
return count + qty + qty * recusiveChildSearch(bagsByColor, childColor);
}, 0);
}
Insert cell
findChildBags = (input, target) => {
const bags = input.split('\n').map(parseRule);
const bagsByColor = bags.reduce(
(map, bag) => map.set(bag.color, bag),
new Map()
);
return recusiveChildSearch(bagsByColor, target);
}
Insert cell
findChildBags(testInput, 'shiny gold')
Insert cell
findChildBags(
`shiny gold bags contain 2 dark red bags.
dark red bags contain 2 dark orange bags.
dark orange bags contain 2 dark yellow bags.
dark yellow bags contain 2 dark green bags.
dark green bags contain 2 dark blue bags.
dark blue bags contain 2 dark violet bags.
dark violet bags contain no other bags.`,
'shiny gold'
)
Insert cell
findChildBags(input, 'shiny gold')
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more