Advent of Code, Day 7: Handy Haversacks

Go to Day 7 Challenge | Go to index
I ran this code in the devtoolbar in Chrome, and the answers were simply outputted to the console. Learn more about my solution.

Part I

"Due to recent aviation regulations, many rules (your puzzle input) are being enforced about bags and their contents; bags must be color-coded and must contain specific quantities of other color-coded bags. Apparently, nobody responsible for these regulations considered how long they would take to enforce!" ref
var rules = document.getElementsByTagName('pre')[0].innerText.split('\n')
var countSet = new Set()

var getBag = (childBag) => {
    var bagReg = new RegExp(`contain[\\sa-z0-9,]*${childBag}`,'i')
    rules
        .filter(r => r.match(bagReg))
        .forEach(r => {
            var containingBag = r.match(/([a-z\s]*)\sbag[s]?\scontain/i)[1].trim()
            countSet.add(containingBag)
            getBag(containingBag)
        })
}

getBag('shiny gold')
console.log(countSet.size)

Part II

"How many individual bags are required inside your single shiny gold bag?"" ref
var rules = document.getElementsByTagName('pre')[0].innerText.split('\n')
var countSet = new Set()

var tree = []
var getBag = (parentBag, count) => {
    var bagReg = new RegExp(`${parentBag}\\sbag[s]?\\scontain`,'i')
    return rules
        .filter(r => r.match(bagReg))
        .map(r => {
            var childrenBags = r.split('contain')[1].split(',')
            return childrenBags.map(c => {
                var child = c.match(/([0-9]+)\s([a-z\s]*)\sbag/i)
                if(child){
                    tree.push({ count: Number(child[1]), total: (Number(child[1]) * count), bag: child[2], parentBag })
                    getBag(child[2], (Number(child[1]) * count))
                }
            }).flat()
        })
        .flat()
}

getBag('shiny gold', 1)
var bagCnt = 0
tree.forEach(t => bagCnt += t.total)
console.log(bagCnt)
 
Created with ❤️ by David Lozzi

Advent of Code
CSS provided by Skeleton
Code highlighting provided by highlight.js

See a problem? Want to share how you solved it? Something else? I want to hear it! Share here!