AoC 2022 D7: No Space Left On Device
| Problem statement | Source code | Tags: Data structuresPuzzle
← Previous Back to AoC Index Next →
Part 1
The main goal is to construct a dirent tree, represented as:
I also added a show for debugging purposes.
The main idea is to process the commands one by one. The state we keep track of is (Dirent, [Text]), representing the full directory tree and the current working directory as a list of path components. Note that the CWD is stored in reverse so that we can push/pop efficiently at the front. logs is the list of commands, each one starting immediately after "$ " and ending before the next "$ ".
cd changes the CWD:
ls updates the tree with the contents of the current directory.
Here are the main steps:
- Go down the tree to reach the CWD
- Iterate through the
lslogs and add entries to the current directory - Traverse back up the tree, updating each parent directory with the modified subtree
First step is to go down:
Second step is to add entries and create a new directory:
parseLsLog parses a single line of ls output:
Third step is to update the subtree back up to the root, each time popping the highest path segment from CWD and updating the corresponding directory:
Since we need to compute the sizes of all directories, I collect all of them in a list:
Part 2
Since the sizes list is ordered from top down, the root size is the head. To make the final size less than 40000000, we need to delete at least rootSize - 40000000. We find the smallest directory that is at least that big by sorting the sizes and using find: