advent-of-code/2022/7/index2.js
2022-12-07 08:12:13 -08:00

75 lines
1.9 KiB
JavaScript

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) => {
const cd = line.match(/^\$ cd (.*)$/);
if(cd) {
if(cd[1] == "..") {
return node.parent;
}
return node.children[cd[1]];
}
const dir = line.match(/^dir (.*)$/);
if(dir) {
node.children[dir[1]] = createNode(node);
}
const file = line.match(/^(\d+) .*$/);
if(file) {
node.localSize += parseFloat(file[1]);
}
return node;
}, files);
const fullSize = totalSmallerDirs(files);
console.log("FULL SIZE: ", fullSize);
console.log("SPACE NEEDED: ", fullSize - 40000000);
const [_, bestDeletionCandidate] = findBestDeletionCandidate(files, fullSize - 40000000);
console.log("Best candidate for deletion is of size: ", bestDeletionCandidate);
})();
const totalSmallerDirs = (node) => {
let totalSize = node.localSize;
totalSize += sum(Object.values(node.children).map(totalSmallerDirs));
if(totalSize <= 100000) {
answer += totalSize;
}
return totalSize;
}
const findBestDeletionCandidate = (node, spaceNeeded) => {
let totalSize = node.localSize;
const childrenResults = Object.values(node.children).map(child => findBestDeletionCandidate(child, spaceNeeded));
totalSize += sum(childrenResults.map(([x]) => x));
const deletionCandidates = childrenResults.map(([_, y]) => y);
deletionCandidates.push(totalSize);
console.log("Deletion Candidates: ", deletionCandidates);
return [totalSize, deletionCandidates.reduce((best, current) => current < best && current >= spaceNeeded ? current : best, Infinity)];
}
const sum = (arr) => arr.reduce((total, num) => total+num, 0);