Advent-of-Code/2022/day1/src/main.rs

40 lines
1.1 KiB
Rust
Raw Normal View History

2023-09-12 09:55:00 +02:00
use std::fs::File;
use std::io::prelude::*;
use std::io::Result;
use std::time::Instant;
fn main() -> Result<()> {
let start_time = Instant::now();
let mut x = File::open("./data").expect("file not found");
let mut content = String::new();
x.read_to_string(&mut content)?;
// Part 1
let mut elf: Vec<i32> = content
.split("\n")
.collect::<Vec<&str>>()
.split(|line| line.is_empty())
.map(|line| line.iter().fold(0, |acc, x| acc + x.parse::<i32>().unwrap()))
.collect();
// Part 1 version 2
// let mut elf: Vec<i32> = content
// .lines()
// .map(|line| line.parse::<i32>().unwrap_or_default())
// .collect::<Vec<i32>>()
// .split(|line| *line == 0)
// .map(|x| x.iter().fold(0, |acc, x| acc + x))
// .collect();
println!("Elf with: {} Calories", elf.iter().max().unwrap());
let duration = start_time.elapsed();
println!("{:?}", duration);
// Part 2
elf.sort();
let max = elf.pop().unwrap();
let mid = elf.pop().unwrap();
let min = elf.pop().unwrap();
println!("{:?}", max + mid + min);
Ok(())
}