Reimplemeted day 7 as a code exercise

This commit is contained in:
John Shaver 2022-12-07 10:04:23 -08:00
parent 0e77c0ae39
commit 04b6452f21
1 changed files with 48 additions and 0 deletions

48
2022/7/take-2.js Normal file
View File

@ -0,0 +1,48 @@
// I wanted to try this one again with a different approach just as an exercise
// in a more complex, but faster way implementing the solutions
const fs = require('fs/promises');
(async () => {
const input = (await fs.readFile("./input.txt", 'utf8')).split("\n");;
const path = [];
const dirsMap = {};
for (const line of input) {
console.log("PATH ", path);
if(line === "$ cd /") {
continue;
}
if(line === "$ cd ..") {
path.pop();
continue;
}
const cdCmd = line.match(/\$ cd (.+)/);
if(cdCmd) {
const [_, cdDir] = cdCmd;
path.push(cdDir);
continue;
}
const file = line.match(/^\d+/);
if(file) {
const [size] = file;
updateDirsOnPath(dirsMap, ["root", ...path], parseFloat(size));
continue;
}
}
console.log("ANSWER: ", sum(Object.values(dirsMap).filter(x => x <= 100000)))
console.log("ANSWER 2: ", Object.values(dirsMap).reduce((best, cur) => cur > dirsMap.root - 40000000 && cur < best ? cur : best, Infinity));
})();
const updateDirsOnPath = (dirsMap, path, size) => {
if(!path.length) return;
const pwd = path.join("/");
dirsMap[path] = (dirsMap[path] || 0) + size;
updateDirsOnPath(dirsMap, path.slice(0, -1), size);
}
const sum = (arr) => arr.reduce((total, num) => total+num, 0);