advent-of-code/2022/7/index.js

66 lines
1.3 KiB
JavaScript
Raw Normal View History

2022-12-07 15:36:06 +00:00
const fs = require('fs/promises');
const createNode = (parent) => {
return {
parent,
children: {},
localSize: 0
};
};
let answer = 0;
(async () => {
const input = await fs.readFile("./input.txt", 'utf8');
const lines = input.split("\n");
const files = createNode();
lines.reduce((node, line) => {
console.log("NODE: ", node);
const cd = line.match(/^\$ cd (.*)$/);
if(cd) {
console.log("CD: ", cd);
if(cd[1] == "..") {
return node.parent;
}
return node.children[cd[1]];
}
const dir = line.match(/^dir (.*)$/);
if(dir) {
console.log("DIR: ", dir);
node.children[dir[1]] = createNode(node);
}
const file = line.match(/^(\d+) .*$/);
if(file) {
node.localSize += parseFloat(file[1]);
}
return node;
}, files);
console.log("FILES: ", files);
const fullSize = totalSmallerDirs(files);
console.log("FULL SIZE: ", fullSize);
console.log("ANSWER: ", answer);
})();
const totalSmallerDirs = (node) => {
let totalSize = node.localSize;
totalSize += sum(Object.values(node.children).map(totalSmallerDirs));
if(totalSize <= 100000) {
answer += totalSize;
}
return totalSize;
}
const sum = (arr) => arr.reduce((total, num) => total+num, 0);