54 lines
1.3 KiB
Rust
54 lines
1.3 KiB
Rust
use std::{
|
|
fs::File,
|
|
io::{prelude::*, BufReader},
|
|
path::Path,
|
|
};
|
|
|
|
fn lines_from_file(filename: impl AsRef<Path>) -> Vec<String> {
|
|
let file = File::open(filename).expect("no such file");
|
|
let buf = BufReader::new(file);
|
|
buf.lines()
|
|
.map(|l| l.expect("Could not parse line"))
|
|
.collect()
|
|
}
|
|
// ---
|
|
|
|
fn main() {
|
|
let lines = lines_from_file("../full/day01.txt");
|
|
part1(&lines);
|
|
part2(&lines);
|
|
}
|
|
|
|
|
|
fn part1(lines: &Vec<String>) {
|
|
let mut totals: Vec<i32> = Vec::new();
|
|
let mut total = 0;
|
|
for line in lines {
|
|
if line.is_empty(){
|
|
totals.push(total);
|
|
total = 0;
|
|
} else {
|
|
total += line.parse::<i32>().unwrap();
|
|
}
|
|
}
|
|
totals.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
|
println!("{:?}", totals[totals.len()-1]);
|
|
}
|
|
|
|
fn part2(lines: &Vec<String>) {
|
|
let mut totals: Vec<i32> = Vec::new();
|
|
let mut total = 0;
|
|
for line in lines {
|
|
if line.is_empty(){
|
|
totals.push(total);
|
|
total = 0;
|
|
} else {
|
|
total += line.parse::<i32>().unwrap();
|
|
}
|
|
}
|
|
totals.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
|
let last3 = &totals[totals.len()-3..];
|
|
let total: i32 = last3.iter().sum();
|
|
println!("{:?}", total);
|
|
}
|