From 0e77c0ae39a24c38500854d1729787c49482d56f Mon Sep 17 00:00:00 2001 From: John Shaver Date: Wed, 7 Dec 2022 08:12:13 -0800 Subject: [PATCH] 7.2 was easier, at least --- 2022/7/index2.js | 75 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 2022/7/index2.js diff --git a/2022/7/index2.js b/2022/7/index2.js new file mode 100644 index 0000000..d71ba97 --- /dev/null +++ b/2022/7/index2.js @@ -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);