7.2 was easier, at least
This commit is contained in:
parent
e10082a33d
commit
0e77c0ae39
1 changed files with 75 additions and 0 deletions
75
2022/7/index2.js
Normal file
75
2022/7/index2.js
Normal file
|
@ -0,0 +1,75 @@
|
||||||
|
|
||||||
|
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);
|
Loading…
Reference in a new issue