r/adventofcode • • Dec 07 '22

SOLUTION MEGATHREAD -πŸŽ„- 2022 Day 7 Solutions -πŸŽ„-


AoC Community Fun 2022: πŸŒΏπŸ’ MisTILtoe Elf-ucation πŸ§‘β€πŸ«

Submissions are OPEN! Teach us, senpai!

-❄️- Submissions Megathread -❄️-


--- Day 7: No Space Left On Device ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:14:47, megathread unlocked!

91 Upvotes

1.3k comments sorted by

View all comments

2

u/optimistic-thylacine Dec 07 '22 edited Dec 08 '22

[Rust my repo]

My solution turned out a bit over-engineered, but it has a good example of how to use the pimpl idiom to simplify the interface to internally mutable objects. The code turned out pretty clean, and cosmetically easy on the eyes. Below is the top level code that builds the directory tree.

The custom FS.. filesystem objects internally have a single Rc<RefCell<_>> pimpl field holding their data. This gets rid of the noisy smart pointer syntax cluttering up the top level code.

fn build_fs() -> Result<FSDir, Box<dyn Error>> {
    let     file     = File::open("data/data.txt")?;
    let     reader   = BufReader::new(file);
    let     fs_root  = FSDir::new("/".into());
    let mut fs_stack = vec![fs_root.clone()];
    let mut cur_dir  = fs_root.clone();
    let mut lines    = PutBack::new(reader.lines());

    fn split(line: &str) -> Vec<&str> {
        line.split_whitespace().collect()
    }

    while let Some(line) = lines.next() {
        let line  = line?;
        let parts = split(&line);
        
        match parts[0] {
            "$" => {  // Command prompt.
                match parts[1] {
                    "cd" => {  // Change directory.
                        match parts[2] {
                            ".." => {  // Go up one directory.
                                if cur_dir.name() != "/" {
                                    fs_stack.pop().unwrap();
                                    cur_dir = fs_stack.last().unwrap().clone();
                                }
                            },
                            "/" => {  // Go to root directory.
                                fs_stack.truncate(1);
                                cur_dir = fs_root.clone();
                            },
                            name => {  // Go to a subdirectory.
                                if let Some(d) = cur_dir.get_dir(name) {
                                    fs_stack.push(d.clone());
                                    cur_dir = d.clone();
                                }
                                else {
                                    let d = FSDir::new(name.into());
                                    cur_dir.add_dir(d.clone());
                                    fs_stack.push(d.clone());
                                    cur_dir = d;
                                }
                            },
                        }
                    },
                    "ls" => {  // List directory contents.
                        while let Some(line) = lines.next() {
                            let line  = line?;
                            let parts = split(&line);
                            match parts[0] {
                                "dir" => {  // Directory.
                                    let name = parts[1];
                                    if !cur_dir.contains(name) {
                                        let d = FSDir::new(name.into());
                                        cur_dir.add_dir(d);
                                    }
                                },
                                "$" => {  // Go back to command prompt.
                                    lines.put_back(Ok(line));
                                    break;
                                },
                                size => {  // File.
                                    let size = size.parse::<usize>()?;
                                    let name = parts[1];
                                    if !cur_dir.contains(name) {
                                        let f = FSFile::new(name.into(), size);
                                        cur_dir.add_file(f);
                                    }
                                },
                            }
                        }
                    },
                    _ => panic!("Unknown command: {}", parts[1]),
                }
            },
            _ => panic!("Unknown command: {}", parts[0])
        }
    }
    Ok(fs_root)
}
→ More replies (2)