aoc/2018/08/part2.js

25 lines
624 B
JavaScript
Raw Permalink Normal View History

2018-12-09 16:38:13 +00:00
const fs = require('fs');
const input = fs.readFileSync('input.txt', 'utf-8').split('\n')[0].split(' ').map(Number);
function parse(arr) {
if (arr[0] == 0) {
return ([2 + arr[1], arr.slice(2, 2 + arr[1]).reduce((a, b) => a + b)]);
}
let children = [];
let pointer = 2;
for (let i = 0; i < arr[0]; i++) {
let child = parse(arr.slice(pointer, arr.length));
pointer += child[0];
children.push(child[1]);
}
let meta = 0;
let indexes = arr.slice(pointer, pointer + arr[1])
for (let i of indexes) {
meta += children[i - 1] || 0;
}
return [pointer + arr[1], meta];
}
let v = parse(input)[1];
console.log(v);