Advent of Code 2022
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.4 KiB

use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Lines;
use clap::Arg;
use clap::Command;
struct Accumulator<B> {
lines: Lines<B>,
current: u32,
}
trait Elvish<B> {
fn elf(self) -> Accumulator<B>;
}
impl<B> Elvish<B> for Lines<B> {
fn elf(self) -> Accumulator<B> {
Accumulator {
lines: self,
current: 0,
}
}
}
impl<B: BufRead> Iterator for Accumulator<B> {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
while let Some(Ok(line)) = self.lines.next() {
let line = line.trim();
if line.is_empty() {
let result = self.current;
self.current = 0;
return Some(result);
} else {
self.current += line.parse::<u32>().unwrap();
}
}
None
}
}
fn main() {
let matches = Command::new("Day1").arg(Arg::new("filename")).get_matches();
let filename = matches
.get_one::<String>("filename")
.expect("Need a filename");
println!("Processing {}...", filename);
let file = File::open(filename).expect("Can't read file");
let reader = BufReader::new(file);
let mut calories = reader.lines().elf().collect::<Vec<u32>>();
calories.sort_by(|a, b| b.cmp(a));
println!("Sum: {:?}", calories.iter().take(3).sum::<u32>())
}