-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpartOne.js
35 lines (28 loc) · 927 Bytes
/
partOne.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const partOne = (input) => {
input = input.split(' ').map(Number);
function buildTree(startIndex) {
const childNodesCount = input[startIndex];
const metadataCount = input[startIndex + 1];
const children = new Array(childNodesCount);
let pointer = startIndex + 2;
for (let i = 0; i < childNodesCount; i++) {
children[i] = buildTree(pointer);
pointer = children[i].next;
}
const next = pointer + metadataCount;
const metadata = input.slice(pointer, next);
return {
children,
metadata,
next
};
}
// Tree-walking function to sum the metadata
function sumMetadata(node) {
const metadataSum = node.metadata.reduce((sum, value) => sum + value);
const childrenSum = node.children.reduce((sum, child) => sum + sumMetadata(child), 0);
return metadataSum + childrenSum;
}
return sumMetadata(buildTree(0));
};
module.exports = partOne;