1
0

Optimized day 7 part 1

This commit is contained in:
Ishan Jain 2022-12-07 17:16:39 +05:30
parent bd982a21c5
commit 26ae929eca
Signed by: ishan
GPG Key ID: 0506DB2A1CC75C27

View File

@ -1,5 +1,4 @@
#![feature(test)] #![feature(test)]
extern crate test; extern crate test;
const INPUTS: [&str; 2] = [ const INPUTS: [&str; 2] = [
@ -23,21 +22,18 @@ fn main() {
} }
fn solution(input: impl Iterator<Item = &'static str>) -> u32 { fn solution(input: impl Iterator<Item = &'static str>) -> u32 {
let mut out = vec![]; let mut out = Vec::with_capacity(100);
let mut stack = vec![]; let mut stack = Vec::with_capacity(100);
let mut current_folder_size = 0; let mut current_folder_size = 0;
for line in input { for line in input {
if line.starts_with("$ ls") || line.starts_with("dir") { match &line[..4] {
continue; "$ ls" | "dir " => continue,
}
if line.starts_with("$ cd") { "$ cd" => match &line[5..6] {
let dir = line.trim_start_matches("$ cd "); // we are supposed to match on .. but this is fine
"." => {
match dir {
".." => {
let v = stack.pop().unwrap(); let v = stack.pop().unwrap();
out.push(current_folder_size); out.push(current_folder_size);
current_folder_size += v; current_folder_size += v;
@ -49,14 +45,15 @@ fn solution(input: impl Iterator<Item = &'static str>) -> u32 {
stack.push(current_folder_size); stack.push(current_folder_size);
current_folder_size = 0; current_folder_size = 0;
} }
} },
} else {
_ => {
let (size, _) = line.split_once(' ').unwrap(); let (size, _) = line.split_once(' ').unwrap();
let size = size.parse::<u32>().unwrap(); let size = size.parse::<u32>().unwrap();
current_folder_size += size; current_folder_size += size;
} }
} }
}
while let Some(v) = stack.pop() { while let Some(v) = stack.pop() {
out.push(current_folder_size); out.push(current_folder_size);