adventofcode2022/src/cli/commands/day001.rs

33 lines
1 KiB
Rust

use crate::cli::PathBuf;
use crate::util::read_lines;
pub fn subcmd_day001(file: &Option<PathBuf>, top: &i32, total: &bool) {
if let Ok(lines) = read_lines(file.as_ref().unwrap().as_path()) {
// Consumes the iterator, returns an (Optional) String
let mut nutri: i32 = 0;
let mut hist: Vec<i32> = Vec::new();
for line in lines {
if let Ok(num) = line {
if num.is_empty() {
hist.push(nutri);
nutri = 0;
} else {
nutri += num.parse::<i32>().unwrap();
}
}
}
hist.sort();
let hist_len = hist.len();
let mut top_total: i32 = 0;
for x in 0..*top{
let index: usize = hist_len - 1 - usize::try_from(x).unwrap();
top_total += hist[index];
println!("{:?}", hist[index]);
}
if *total{
println!("Total:");
println!("{:?}", top_total);
}
}
}