Read input from file
This commit is contained in:
parent
108ef47eb5
commit
4c040d67b3
1
.gitignore
vendored
1
.gitignore
vendored
@ -1 +1,2 @@
|
||||
/target
|
||||
/input
|
||||
|
@ -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);
|
||||
|
@ -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!(
|
||||
|
19
src/day1.rs
19
src/day1.rs
@ -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);
|
||||
}
|
||||
|
13
src/util.rs
13
src/util.rs
@ -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(());
|
||||
|
Loading…
x
Reference in New Issue
Block a user