-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemory.js
60 lines (43 loc) · 1.08 KB
/
memory.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const sumMetadata = ({ children, metadata }) => {
let sum = 0;
if (children.length) {
children.forEach((child) => {
sum += sumMetadata(child);
});
}
return sum + metadata.reduce((a, b) => a + b, 0);
};
const nodeLength = ({ children, metadata }) => {
let length = 0;
if (children.length) {
children.forEach((child) => {
length += nodeLength(child);
});
}
return 2 + length + metadata.length;
};
const parse = (parts) => {
const childNodes = parts[0];
const metadataEntries = parts[1];
const children = [];
let position = 2;
if (childNodes > 0) {
for (let i = 0; i < childNodes; i++) {
const innerParts = parts.slice(position, parts.length);
const node = parse(innerParts);
position += nodeLength(node);
children.push(node);
}
}
const metadata = parts.slice(position, position + metadataEntries);
return {
children,
metadata,
};
};
const memory = (input) => {
const parts = input.split(' ').map(Number);
const tree = parse(parts);
return sumMetadata(tree);
};
module.exports = memory;