AdventOfCode2022/01/main.rs

77 lines
2.0 KiB
Rust
Raw Normal View History

2022-12-01 12:33:12 +00:00
#![allow(dead_code)]
use std::fs::File;
use std::io;
use std::io::BufRead;
use std::path::Path;
use std::time::Instant;
fn main() {
let now = Instant::now();
part_one();
let part_one_duration = now.elapsed();
part_two();
let part_two_duration = now.elapsed();
println!(
"p1: {}ms, p2: {}ms",
part_one_duration.as_millis(),
2022-12-02 12:46:29 +00:00
(part_two_duration - part_one_duration).as_millis()
2022-12-01 12:33:12 +00:00
);
}
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
P: AsRef<Path>,
{
2022-12-01 13:01:59 +00:00
// note that this discards a final newline
2022-12-01 12:33:12 +00:00
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
2022-12-01 13:01:59 +00:00
fn part_one() {
if let Ok(lines) = read_lines("./inputs/input") {
let mut biggest = 0;
let mut accumulator = 0;
for line in lines {
if let Ok(calories) = line {
if calories != "" {
accumulator += calories.parse::<u32>().unwrap();
} else {
if accumulator > biggest {
biggest = accumulator
}
accumulator = 0;
}
}
}
// catching final elf
if accumulator > biggest {
biggest = accumulator
}
println!("{}", biggest);
}
}
2022-12-01 12:33:12 +00:00
2022-12-01 13:01:59 +00:00
fn part_two() {
if let Ok(lines) = read_lines("./inputs/input") {
let mut elves = Vec::new();
let mut accumulator = 0;
for line in lines {
if let Ok(calories) = line {
if calories != "" {
accumulator += calories.parse::<u32>().unwrap();
} else {
elves.push(accumulator);
accumulator = 0;
}
}
}
// catching final elf
elves.push(accumulator);
elves.sort_unstable();
println!(
"{}",
elves.pop().unwrap() + elves.pop().unwrap() + elves.pop().unwrap()
);
}
}