|
|
|
@ -1,10 +1,47 @@
|
|
|
|
|
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 |
|
|
|
@ -15,23 +52,5 @@ fn main() {
|
|
|
|
|
let file = File::open(filename).expect("Can't read file"); |
|
|
|
|
let reader = BufReader::new(file); |
|
|
|
|
|
|
|
|
|
let mut max_calories = 0; |
|
|
|
|
let mut elf_calories = 0; |
|
|
|
|
|
|
|
|
|
for line in reader.lines() { |
|
|
|
|
let line = line.unwrap(); |
|
|
|
|
let line = line.trim(); |
|
|
|
|
|
|
|
|
|
// XXX I want to do this with an iterator!
|
|
|
|
|
if line.is_empty() { |
|
|
|
|
if elf_calories > max_calories { |
|
|
|
|
max_calories = elf_calories; |
|
|
|
|
} |
|
|
|
|
elf_calories = 0; |
|
|
|
|
} else { |
|
|
|
|
println!("Line: {}", line); |
|
|
|
|
elf_calories += line.parse::<u32>().unwrap(); |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
println!("Max: {}", max_calories); |
|
|
|
|
println!("Max: {:?}", reader.lines().elf().max()) |
|
|
|
|
} |
|
|
|
|