diff --git a/.gitignore b/.gitignore index ea8c4bf..3ceb93d 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /target +/input diff --git a/src/bin/d1p1.rs b/src/bin/d1p1.rs index 1d36091..77f9bad 100644 --- a/src/bin/d1p1.rs +++ b/src/bin/d1p1.rs @@ -1,7 +1,8 @@ use aoc22::day1; +use aoc22::util; fn main() { - let elves = day1::read_elves(); + let elves = day1::parse_elves(&util::parse_input()); let max = elves.iter().max().unwrap(); println!("The elf with the most calories is carrying {} cal", max); diff --git a/src/bin/d1p2.rs b/src/bin/d1p2.rs index ccea78f..52cd5b2 100644 --- a/src/bin/d1p2.rs +++ b/src/bin/d1p2.rs @@ -4,7 +4,7 @@ use aoc22::util; const N_ELVES: usize = 3; fn main() { - let elves = day1::read_elves(); + let elves = day1::parse_elves(&util::parse_input()); let max_vals = util::max_n(elves.as_slice(), N_ELVES).unwrap(); println!( diff --git a/src/day1.rs b/src/day1.rs index e4cfa76..ae6dce2 100644 --- a/src/day1.rs +++ b/src/day1.rs @@ -1,24 +1,13 @@ -use std::io; - -pub fn read_elves() -> Vec { - println!("What's the calorie list?"); - let lines = io::stdin().lines(); - let mut was_empty = false; +pub fn parse_elves(input: &String) -> Vec { + let lines = input.lines(); let mut elves = vec![0]; for line in lines { - let line_s = line.unwrap(); - if line_s.is_empty() { - if was_empty { - break; - } + if line.is_empty() { elves.push(0); - was_empty = true; continue; - } else { - was_empty = false; } - let calories: u32 = line_s.parse().expect("Wanted a number"); + let calories: u32 = line.parse().expect("Wanted a number"); let prev_calories = elves.pop().unwrap(); elves.push(prev_calories + calories); } diff --git a/src/util.rs b/src/util.rs index d67db2a..e066d5d 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,3 +1,16 @@ +use std::env; +use std::fs; + +pub fn parse_input() -> String { + let args: Vec = env::args().collect(); + let input_path = args + .get(1) + .expect(format!("Usage: {} INPUT-FILE", args.get(0).unwrap()).as_str()); + + fs::read_to_string(input_path) + .expect(format!("Couldn't read input file {}", input_path).as_str()) +} + pub fn max_n(slice: &[T], n: usize) -> Result, ()> { if n == 0 || n > slice.len() { return Err(());