From ee4c8035e1f31ca1c5e856277d9706f7730785d9 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Wed, 8 Dec 2021 14:40:28 +0100 Subject: Use function for part 1 --- day4/src/main.rs | 82 +++++++++++++++++++++++++++++--------------------------- 1 file changed, 43 insertions(+), 39 deletions(-) (limited to 'day4/src/main.rs') diff --git a/day4/src/main.rs b/day4/src/main.rs index aed66ec..6e44c10 100644 --- a/day4/src/main.rs +++ b/day4/src/main.rs @@ -1,44 +1,7 @@ use std::fs::File; use std::io::{BufRead, BufReader}; -fn main() -> std::io::Result<()> { - let file = File::open("input.txt")?; - let reader = BufReader::new(file); - let mut lines = reader.lines(); - - let mut inputs: Vec<_> = lines - .next() - .unwrap() - .unwrap() - .trim() - .split(',') - .map(|x| x.parse::().unwrap()) - .collect::>(); - - let mut grids: Vec> = vec![]; - let mut n: usize = 0; - - lines.next(); // Ignore the first empty line - while let Some(line) = lines.next() { - let mut line = line.unwrap(); - grids.push(Vec::with_capacity(5 * 5)); - - for _ in 0..5 { - grids[n].extend( - line.trim() - .split(' ') - .filter(|x| !x.is_empty()) - .map(|x| x.parse::().unwrap()) - .collect::>(), - ); - line = match lines.next() { - Some(x) => x.unwrap(), - None => "".to_string(), - }; - } - n += 1; - } - +fn part1(grids: &Vec>, mut inputs: Vec) -> u32 { let mut values = Vec::::new(); for _ in 0..4 { @@ -97,7 +60,48 @@ fn main() -> std::io::Result<()> { sum += x; } - println!("{}", sum * values.pop().unwrap()); + sum * values.pop().unwrap() +} + +fn main() -> std::io::Result<()> { + let file = File::open("input.txt")?; + let reader = BufReader::new(file); + let mut lines = reader.lines(); + + let inputs: Vec<_> = lines + .next() + .unwrap() + .unwrap() + .trim() + .split(',') + .map(|x| x.parse::().unwrap()) + .collect::>(); + + let mut grids: Vec> = vec![]; + let mut n: usize = 0; + + lines.next(); // Ignore the first empty line + while let Some(line) = lines.next() { + let mut line = line.unwrap(); + grids.push(Vec::with_capacity(5 * 5)); + + for _ in 0..5 { + grids[n].extend( + line.trim() + .split(' ') + .filter(|x| !x.is_empty()) + .map(|x| x.parse::().unwrap()) + .collect::>(), + ); + line = match lines.next() { + Some(x) => x.unwrap(), + None => "".to_string(), + }; + } + n += 1; + } + + println!("{}", part1(&grids, inputs.clone())); Ok(()) } -- cgit v1.2.3-18-g5258