Skip to content

Instantly share code, notes, and snippets.

@Mellen
Last active December 8, 2020 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mellen/edd62f5310b2576c868f8a1cb366b938 to your computer and use it in GitHub Desktop.
Save Mellen/edd62f5310b2576c868f8a1cb366b938 to your computer and use it in GitHub Desktop.
function shinyGoldContainersp1()
{
const input = document.querySelector('pre').innerHTML;
const containers = input.match(/(\w+ \w+) bags contain (?:(?:\d+ (\w+ \w+)) bag(?:s?)[.,](?: ?))+/g);
let bags = new Set([]);
let checkedBags = new Set([]);
let newBags = findHoldersFor(containers, 'shiny gold');
checkedBags.add('shiny gold');
let lastSize = 0;
while(lastSize != checkedBags.size)
{
lastSize = checkedBags.size;
newBags.forEach(bag =>
{
bags.add(bag);
});
let next = [];
while(newBags.length > 0)
{
let bag = newBags.pop();
next = next.concat(findHoldersFor(containers, bag));
checkedBags.add(bag);
}
newBags = next;
}
function findHoldersFor(containers, bagDesc)
{
return containers.map(container =>
{
let bagMatch = container.match(new RegExp(`(\\w+ \\w+) bags contain .*(?:(?:\\d+ ${bagDesc}) bag(?:s?)[.,](?: ?)).*`));
return (bagMatch??[])[1]??'';
}).filter(b => b != '');
}
return bags.size;
}
function shinyGoldContainersp2()
{
let input = document.querySelector('pre').innerHTML.trim();
let result = 0;
let bagNodes = new Map();
let ends = input.matchAll(/(\w+ \w+) bags contain no other bags\./g);
[...ends].forEach(bag =>
{
let n = new node(bag[1], []);
bagNodes.set(bag[1], n);
});
let rules = input.split('\n').filter(line => !line.endsWith('other bags.'));
rules.forEach(rule =>
{
let halves = rule.split(' bags contain ');
let bag = halves[0];
let curnode = bagNodes.has(bag)?bagNodes.get(bag):(new node(bag, []));
if(!bagNodes.has(bag))
{
bagNodes.set(bag, curnode);
}
let parts = [...halves[1].matchAll(/(?:(?<count>\d+) (?<colour>\w+ \w+))/g)];
parts.forEach(part =>
{
let colour = part.groups.colour;
let count = parseInt(part.groups.count, 10);
let newNode;
if(!bagNodes.has(colour))
{
newnode = new node(colour, []);
bagNodes.set(colour, newnode);
}
else
{
newnode = bagNodes.get(colour);
}
for(let i = 0; i < count; i++)
{
curnode.nextbags.push(newnode);
}
});
});
return bagNodes.get('shiny gold').containsCount();
}
function node(bag, nextbags)
{
this.bag = bag;
this.nextbags = nextbags;
}
node.prototype.containsCount = function()
{
let count = this.nextbags.length;
count += this.nextbags.reduce((sum, bag) => sum + bag.containsCount(), 0);
return count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment