63 lines
1.7 KiB
Rust
63 lines
1.7 KiB
Rust
// From rust by example
|
|
|
|
use std::fs::File;
|
|
use std::io::{self, BufRead};
|
|
use std::path::Path;
|
|
|
|
fn aoc_day1(path : &str, n : i64) -> i64 {
|
|
let mut max_calories : [i64; 3] = [0, 0, 0];
|
|
let mut calories : i64 = 0;
|
|
if let Ok(lines) = read_lines(path) {
|
|
for line in lines {
|
|
if let Ok(scalories) = line {
|
|
println!("{}", scalories);
|
|
println!("[{}, {}, {}]", max_calories[0], max_calories[1], max_calories[2]);
|
|
if scalories.len() == 0 {
|
|
if calories > max_calories[0] {
|
|
max_calories[0] = calories;
|
|
max_calories.sort();
|
|
}
|
|
calories = 0;
|
|
} else {
|
|
let snack_calories = scalories.parse::<i64>().unwrap();
|
|
calories += snack_calories;
|
|
}
|
|
}
|
|
}
|
|
// eof
|
|
if calories > max_calories[0] {
|
|
max_calories[0] = calories;
|
|
max_calories.sort();
|
|
}
|
|
}
|
|
if n == 1 {
|
|
return max_calories[2];
|
|
} else {
|
|
return max_calories.iter().sum();
|
|
}
|
|
}
|
|
|
|
// The output is wrapped in a Result to allow matching on errors
|
|
// Returns an Iterator to the Reader of the lines of the file.
|
|
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
|
|
where P: AsRef<Path>, {
|
|
let file = File::open(filename)?;
|
|
Ok(io::BufReader::new(file).lines())
|
|
}
|
|
|
|
fn main() {
|
|
aoc_day1("input.txt", 1);
|
|
}
|
|
|
|
#[test]
|
|
fn day1input() {
|
|
assert_eq!(aoc_day1("input.txt", 1), 69206);
|
|
assert_eq!(aoc_day1("input.txt", 3), 197400);
|
|
}
|
|
|
|
#[test]
|
|
fn example() {
|
|
assert_eq!(aoc_day1("example.txt", 1), 24000);
|
|
assert_eq!(aoc_day1("example.txt", 3), 45000);
|
|
}
|