diff --git a/2022/7/take-2.js b/2022/7/take-2.js new file mode 100644 index 0000000..3e66171 --- /dev/null +++ b/2022/7/take-2.js @@ -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);