Read input from file

This commit is contained in:
jazzpi 2022-12-13 13:47:31 +01:00
parent 108ef47eb5
commit 4c040d67b3
5 changed files with 21 additions and 17 deletions

1
.gitignore vendored
View File

@ -1 +1,2 @@
/target
/input

View File

@ -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);

View File

@ -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!(

View File

@ -1,24 +1,13 @@
use std::io;
pub fn read_elves() -> Vec<u32> {
println!("What's the calorie list?");
let lines = io::stdin().lines();
let mut was_empty = false;
pub fn parse_elves(input: &String) -> Vec<u32> {
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);
}

View File

@ -1,3 +1,16 @@
use std::env;
use std::fs;
pub fn parse_input() -> String {
let args: Vec<String> = 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<T: Ord + Copy>(slice: &[T], n: usize) -> Result<Vec<T>, ()> {
if n == 0 || n > slice.len() {
return Err(());