This commit is contained in:
Dory 2024-03-10 15:39:05 -07:00
parent b4ec1ca428
commit 73c5cb9e62
5 changed files with 1230 additions and 0 deletions

7
day7/Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "day7"
version = "0.1.0"

8
day7/Cargo.toml Normal file
View File

@ -0,0 +1,8 @@
[package]
name = "day7"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

1101
day7/input.txt Normal file

File diff suppressed because it is too large Load Diff

91
day7/src/main.rs Normal file
View File

@ -0,0 +1,91 @@
use std::env;
use std::fs::File;
use std::io::{self, BufRead};
use std::collections::HashMap;
fn main() {
let file = File::open(&env::args().nth(1).unwrap()).unwrap();
let mut lines = io::BufReader::new(file).lines();
let mut tree = DirTree::new();
let mut cwd = 0;
loop {
let tokens: Vec<_> = if let Some(Ok(l)) = lines.next() {
l.split_whitespace().map(String::from).collect()
} else { break; };
if tokens[0] == "$" {
if tokens[1] == "cd" {
if tokens[2] == ".." {
cwd = tree.inodes[cwd].parent.unwrap();
} else if tokens[2] == "/" {
cwd = 0;
} else {
let subdir = tree.inodes[cwd].subdirs[&tokens[2]];
cwd = subdir;
}
} else if tokens[1] == "ls" {
continue;
}
} else if tokens[0] == "dir" {
tree.add_subdir_to(cwd, tokens[1].clone());
} else {
tree.add_file_to(
cwd,
tokens[1].clone(),
tokens[0].parse::<usize>().unwrap());
}
}
let sum: usize = (0..tree.inodes.len())
.map(|inode| tree.size_of(inode))
.filter(|size| *size <= 100000)
.sum();
println!("{:?}", sum);
}
#[derive(Debug)]
struct Dir {
pub files: HashMap<String, usize>, // file name and size
pub subdirs: HashMap<String, usize>, // dir name and index into arena
pub parent: Option<usize>, // index into arena
}
#[derive(Debug)]
struct DirTree {
inodes: Vec<Dir>,
}
impl DirTree {
fn new() -> Self {
let newdir = Dir {
files: HashMap::new(),
subdirs: HashMap::new(),
parent: None,
};
DirTree { inodes: vec![newdir] }
}
fn add_subdir_to(&mut self, idx: usize, name: String) {
let newidx = self.inodes.len();
let newdir = Dir {
files: HashMap::new(),
subdirs: HashMap::new(),
parent: Some(idx),
};
self.inodes.push(newdir);
self.inodes[idx].subdirs.insert(name, newidx);
}
fn add_file_to(&mut self, idx: usize, name: String, size: usize) {
self.inodes[idx].files.insert(name, size);
}
fn size_of(&self, inode: usize) -> usize {
let size_files: usize = self.inodes[inode].files.values().sum();
let size_dirs: usize = self.inodes[inode].subdirs.values()
.fold(0, |acc, subdir_inode| acc + self.size_of(*subdir_inode));
size_files + size_dirs
}
}

23
day7/test.txt Normal file
View File

@ -0,0 +1,23 @@
$ cd /
$ ls
dir a
14848514 b.txt
8504156 c.dat
dir d
$ cd a
$ ls
dir e
29116 f
2557 g
62596 h.lst
$ cd e
$ ls
584 i
$ cd ..
$ cd ..
$ cd d
$ ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k