Published
Edited
Dec 8, 2020
Insert cell
Insert cell
inputToList(exampleinput)
Insert cell
parseBag("2 vibrant plum bags.")
Insert cell
inputToList2(exampleinput)
Insert cell
rcount(inputToList2(exampleinput), ["shiny gold"], 1)
Insert cell
rcount(inputToList2(exampleinput), ["dark olive"], 1)
Insert cell
// mutable mcount = 0
Insert cell
function rcount (arr, bags, count) {
let hits = []
for(let i = 0; i < arr.length; i++) {
if(bags.includes(arr[i][0])) {
hits.push(arr[i])
}
}
for(let i = 0; i < hits.length; i++) {
count+= hits[i][2]
}
// count += count * hits.length
let recurse = hits.filter(hit => hit[1]!=null)
if(recurse.length==0) return count
for(let i = 0; i < recurse.length; i++) {
count += arr[i][2] * rcount(arr, [recurse[i][1]], count)
}
return count
// return rcount(arr, hits, count)
}
Insert cell
// function rcount (arr, bags, count) {
// let hits = []
// for(let i = 0; i < arr.length; i++) {
// if(bags.includes(arr[i][0])) {
// hits.push(arr[i][1])
// count += arr[i][2] + arr[i][2] * rcount(arr, [arr[i][1]], count)
// }
// }
// if(hits.length==0) return 1
// return hits
// // return rcount(arr, hits, count)
// }
Insert cell
inputToList2 = str => str
.split("\n")
.map(getParentsWithNum)
.reduce((acc, inc) => acc.concat(inc), [])
Insert cell
parseBag = str => {
let name = str.match(/(?<=\d+ ).*/)[0].replace(/ (bags|bag)(.|)/, "")
let num = +str.match(/\d+/)[0]
return [name, num]
}
Insert cell
getParentsWithNum("shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.")
Insert cell
getParentsWithNum = str => {
const [name, rest]= str.split(" bags contain ")
const bags = rest.split(",")
if(rest=="no other bags.") return [[name, null, 0]]
return rest.split(",").map(parseBag).map(parent => [name].concat(parent))
}
Insert cell
Insert cell
deduplicateArray = arr => new Set(arr)
Insert cell
inputToList(exampleinput)
Insert cell
solvep1(input)("shiny gold")
Insert cell
solvep1(exampleinput)("shiny gold")
Insert cell
getLinks(inputToList(exampleinput), ["shiny gold"], [])
Insert cell
solvep1 = data => bagcolor => deduplicateArray(getLinks(inputToList(data), [bagcolor], [])).size
Insert cell
inputToList = str => str
.split("\n")
.map(getParents)
.reduce((acc, inc) => acc.concat(inc), [])
Insert cell
getParents = str => {
const [name, rest]= str.split(" bags contain ")
if(rest==null) console.log(rest)
const bags = rest.split(",")
if(rest=="no other bags.") return [[name, null]]
const parents = rest.split(",")
.map(bag => bag.match(/(?<=\d+ ).*/)[0]
.replace(/ (bags|bag)(.|)/, "")
)
return parents.map(parent => [name, parent])
}
Insert cell
Insert cell
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