This problem is a noticeable step up in difficulty from previous days. While beginner and self-taught programmers may have found success earlier in the season through sheer determination, without some guidance they are likely to struggle with day 7. This post introduces a couple tools and techniques that ought to make solving easier.
The problem asks solvers to parse the log from a terminal session, which includes cd
and ls
commands, and determine the total size of directories, including their subdirectories.
$ cd / $ ls dir a 100 z.txt $ cd a $ ls 200 y.txt
In this example, directory /
contains one directory: a
, and one file: z.txt
, which is 100 bytes in size.
Directory /a
contains one file: y.txt
, which is 200 bytes in size.
Therefore, /a
has a total size of 200
bytes, and /
has a total size of 100 + 200 = 300
bytes.
Let's create some terminal input that only contains cd
commands.
cd / cd a cd b cd .. cd c cd d cd .. cd .. cd .. cd e
Exercise: Write down the current fully-qualified (e.g. /a/b
instead of just b) working directory at each step.
Solution: (hover to view)
/ /a /a/b /a /a/c /a/c/d /a/c /a / /e
It's likely that writing this out by hand was easy. Do you know how to write a program to do it?
Exercise: Try to write a short program that reads the input and prints the fully-qualified directory at each step.
Don't spend more than 20 minutes on this. If you want a hint, or you're ready to move on, Click here.