import { readFileSync } from 'fs'; import { join } from 'path'; enum ftype { File = 1, Directory, } class File { fileType: ftype; name: string; size: number; parent?: string; children?: string[]; constructor(fileType: ftype, name: string, size: number, parent?: string, children?: string[]) { this.fileType = fileType; this.name = name; this.size = size; this.parent = parent; this.children = children; } } const fileString = readFileSync(join(__dirname, "input"), 'utf-8'); var commands = fileString.trim().split("$ "); commands = commands.filter(val => { return val.length > 0; }) commands = commands.map(val => { return val.trim(); }) var parsedCommandsSp = commands.map(val => { return val.split("\n"); }) var parsedCommands = parsedCommandsSp.map(val => { return val.map(vval => { return vval.split(" "); }); }) var files = {}; var currentDir = "" function getDirSize(dirname: string): number { const f = files[dirname]; if (f.fileType != ftype.Directory) { return -1; } var sum = 0; for (const c of f.children) { if (files[c].fileType == ftype.File) { sum += files[c].size; } else { sum += getDirSize(c); } } return sum; } function generateFullPath(fname: string): string { if (fname == '') { return ''; } return generateFullPath(files[fname].parent) + fname; } for (var i = 0; i < parsedCommands.length; i++) { const commandSet = parsedCommands[i] if (commandSet[0][0] == "cd") { var dname = commandSet[0][1] if (dname == "..") { currentDir = files[currentDir].parent } else { const fname = generateFullPath(currentDir) + dname; if (!(fname in files)) { files[fname] = new File( ftype.Directory, fname, 0, currentDir, [] ); if (currentDir != "") { files[currentDir].children.push(fname); } } currentDir = fname; } } else if (commandSet[0][0] == "ls") { for (const fs of commandSet.slice(1)) { const typeOrSize = fs[0]; const name = fs[1]; const fname = generateFullPath(currentDir) + name; if (typeOrSize == 'dir') { if (!(fname in files)) { files[fname] = new File( ftype.Directory, fname, 0, currentDir, [] ); if (currentDir != "") { files[currentDir].children.push(fname); } } } else { const fsize: number = +typeOrSize; if (!(fname in files)) { files[fname] = new File( ftype.File, fname, fsize, currentDir, [] ); if (currentDir != "") { files[currentDir].children.push(fname); } } } } } } const LIMIT = 100000; var fsum = 0; var sizes = []; for (const key in files) { const f = files[key]; if (f.fileType == ftype.Directory) { const s = getDirSize(key); sizes.push(s); if (s <= LIMIT) { fsum += s; } } } console.log(fsum); const TOTAL = 70000000; const THRESH = 30000000; const FREE = TOTAL - getDirSize("/"); var small = 1000000000000000; for (const size of sizes) { if ((FREE + size) > THRESH) { if (size < small) { small = size; } } } console.log(small);