Skip to content

Instantly share code, notes, and snippets.

@wkei
Last active December 14, 2018 07:33
Show Gist options
  • Save wkei/aa37d84fa8920709a69baa80e14bf94d to your computer and use it in GitHub Desktop.
Save wkei/aa37d84fa8920709a69baa80e14bf94d to your computer and use it in GitHub Desktop.
// https://adventofcode.com/2018/day/8
// https://jsfiddle.net/keipixel/fuyhq4az/
const data = '2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2'
// {
// meta: [1, 1, 2],
// children: [
// {
// meta: [10, 11, 12],
// children: []
// },
// {
// meta: [2],
// children: [
// {
// meta: [99],
// children: []
// }
// ]
// }
// ]
// }
const treeify = d => {
const node = {
meta: [],
children: []
}
const childCount = d.shift()
const metaCount = d.shift()
// console.log(`has ${metaCount} meta entries & ${childCount} children`)
if (childCount) {
for (let i = 0; i < childCount; i++) {
node.children.push(treeify(d))
}
}
// all children should be deleted
node.meta = d.splice(0, metaCount)
return node
}
const sumMetas = tree => {
const sum = tree.meta.reduce((sum, i) => sum + 1 * i, 0)
if (tree.children) {
return sum + tree.children.map(child => sumMetas(child)).reduce((sum, i) => sum + 1 * i, 0)
}
return sum
}
const getRootValue = tree => {
return tree.meta
.map(meta => {
const node = tree.children[meta - 1]
// console.log(node)
if (node) {
if (node.children.length === 0) {
return node.meta.reduce((sum, i) => sum + 1 * i, 0)
} else {
return getRootValue(node)
}
}
return 0
})
.reduce((sum, i) => sum + 1 * i, 0)
}
const tree = treeify(data.split(' '))
console.log(tree)
// 8.1
const sum = sumMetas(tree)
console.log(sum)
// 8.2
const value = getRootValue(tree)
console.log(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment