AdventOfCode2022/07/main.rs

100 lines
2.7 KiB
Rust

#![allow(dead_code)]
use std::collections::HashMap;
use std::fs::File;
use std::io;
use std::io::BufRead;
use std::path::Path;
use std::time::Instant;
#[derive(Debug, Clone)]
struct ElfFile {
name: String,
size: u32,
}
#[derive(Debug, Clone)]
struct Folder<'a> {
name: String,
files: HashMap<String, ElfFile>,
folders: HashMap<String, &'a Folder<'a>>,
}
fn main() {
let now = Instant::now();
part_one();
let part_one_duration = now.elapsed();
part_two();
let part_two_duration = now.elapsed();
println!(
"p1: {}ms, p2: {}ms",
part_one_duration.as_millis(),
(part_two_duration - part_one_duration).as_millis()
);
}
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
P: AsRef<Path>,
{
// note that this discards a final newline
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
fn ElfFile_FromStr(s: &str) -> ElfFile {
let mut f = s.split(" ");
return ElfFile {
size: f.next().unwrap().parse::<u32>().unwrap(),
name: f.next().unwrap().to_string(),
};
}
fn newFolder(s: &str) -> Folder {
return Folder {
name: s.to_string(),
files: HashMap::new(),
folders: HashMap::new(),
};
}
fn part_one() {
if let Ok(lines) = read_lines("./inputs/input") {
let mut tree = Folder {
name: "/".to_string(),
files: HashMap::new(),
folders: HashMap::new(),
};
let mut stack: Vec<&mut Folder> = vec![&mut tree];
for line in lines {
if let Ok(command) = line {
match command.as_str() {
"$ cd /" => continue, // skip start
"$ ls" => continue, // we can assume this if we're not moving between directories
"$ cd .." => {
// stack.pop();
}
s if s.starts_with("$ cd ") => {
println!("push {}\n", s.split(" ").nth(2).unwrap())
}
s if s.starts_with("dir ") => {
let f = stack.pop().unwrap();
let ef = newFolder(s.split(" ").nth(1).unwrap());
f.folders.insert(ef.name.clone(), &ef);
stack.push(f);
}
s => {
// otherwise it must be a file
let f = stack.pop().unwrap();
let ef = ElfFile_FromStr(s);
f.files.insert(ef.name.clone(), ef);
stack.push(f);
}
};
}
}
println!("{:?}", tree);
}
}
fn part_two() {}