Published
Edited
Dec 12, 2020
1 fork
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
parsed = {
const lines = input.trim().split('\n')
return new Map(lines.map(l => {
const [name, to] = l.replace(/ bags?/g, '').split(' contain ')
const children = to.split(', ')
.map(t => {
const [, n, name] = t.replace('.', '').match(/(\d+) (.*)/) || []
return n && {name, n: +n}
})
.filter(d => d)
return [name, children]
}))
}
Insert cell
roots = {
const parented = new Set([...parsed.values()].flat().map(d => d.name))
return [...parsed.keys()].filter(x => !parented.has(x))
}
Insert cell
data = tree(root)
Insert cell
function tree(name) {
const children = parsed.get(name).map(({name}) => tree(name))
return { name, children, value: children.length ? undefined : 1 }
}
Insert cell
import { drag, height } with { data } from '@d3/force-directed-tree'
Insert cell
import { chart as treemap } with { data } from '@d3/treemap'
Insert cell
treemap
Insert cell
import { chart as circlePacking } with { data } from '@d3/circle-packing'
Insert cell
circlePacking
Insert cell
Insert cell
rules = input.trim().split('\n').map(r => {
const [from, to] = r.replace(/ bags?/g, '').split(' contain ')
return {from, to: to.split(', ').map(t => t.replace(/\d+ |\./g, ''))}
})
Insert cell
upwards = d3.rollup(rules.flatMap(({from, to}) => to.map(to => ({from, to}))), r => r.map(d => d.from), d => d.to)
Insert cell
function up(bag) {
const r = [bag]
if (upwards.has(bag))
for (const u of upwards.get(bag))
r.push(...up(u))
return r
}
Insert cell
part1 = new Set(up('shiny gold')).size - 1
Insert cell
function down(bag) {
let sum = 1
if (parsed.has(bag))
for (const {name, n} of parsed.get(bag))
sum += n * down(name)
return sum
}
Insert cell
part2 = down('shiny gold') - 1
Insert cell
Insert cell
Insert cell
Insert cell
d3 = require('d3@6')
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