From 6ec6ac420021567833582c3dd69b6cd5358feb0e Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Thu, 1 Dec 2022 15:29:22 -0500 Subject: [PATCH] Complete part 2 of day 1 --- day1/src/main.rs | 47 ++++++++++++++++++++++++++++++----------------- 1 file changed, 30 insertions(+), 17 deletions(-) diff --git a/day1/src/main.rs b/day1/src/main.rs index cf48d1e..e31b1b9 100644 --- a/day1/src/main.rs +++ b/day1/src/main.rs @@ -1,34 +1,47 @@ use std::error::Error; use std::fs; -fn main() -> Result<(), Box> { - let file_str = fs::read_to_string("input.txt")?; - let mut elves: Vec> = Vec::new(); +fn get_elves(raw: &str) -> Vec> { + raw.split("\n\n") + .map(|raw_elf| { + raw_elf + .split('\n') + .filter(|value| value.len() > 0) + .map(move |value| value.parse::().unwrap()) + .collect::>() + }) + .collect() +} + +fn get_elf_totals(elves: &Vec>) -> Vec { let mut totals: Vec = Vec::new(); - for raw_elf in file_str.split("\n\n") { - let elf: Vec = raw_elf.split('\n') - .filter(|value| value.len() > 0) - .map(move |value| { - value.parse::().unwrap() - }) - .collect(); - + for elf in elves { let sum = elf .clone() .into_iter() .reduce(|accum, item| accum + item) .unwrap(); - - elves.push(elf); - totals.push(sum); + totals.push(sum) } - let most = totals.iter().max().unwrap(); + totals +} - println!("{:?}{:?}", elves, totals); - println!("Max calories: {}", most); +fn main() -> Result<(), Box> { + let file_str = fs::read_to_string("input.txt")?; + let elves = get_elves(&file_str); + let mut totals: Vec = get_elf_totals(&elves); + totals.sort(); + totals.reverse(); + + // let most = totals.iter().max().unwrap(); + let most = totals[0]; + let top3 = totals[0] + totals[1] + totals[2]; + + println!("Part 1: Most calories for one elf: {}", most); + println!("Part 2: Calories for top three elves: {}", top3); Ok(()) }