1
0
mirror of https://gitlab.com/MisterBiggs/aoc_2022-rust.git synced 2025-06-16 07:06:47 +00:00
Aoc-2022-Rust/src/day1.rs
2022-12-01 15:59:11 -07:00

87 lines
1.4 KiB
Rust

use std::fs;
pub fn run() {
println!("Day 1:");
let input = fs::read_to_string("./inputs/day1.txt").expect("Could not read file");
println!("\tPart 1: {}", part1(&input));
println!("\tPart 2: {}", part2(&input));
}
fn part1(food_input: &str) -> usize {
food_input
.split("\n\n")
.collect::<Vec<&str>>()
.into_iter()
.map(|elf| {
elf.split_whitespace()
.map(|food| food.parse::<usize>().unwrap())
.sum()
})
.collect::<Vec<usize>>()
.into_iter()
.max()
.unwrap()
}
fn part2(food_input: &str) -> usize {
let mut elves_calories = food_input
.split("\n\n")
.collect::<Vec<&str>>()
.into_iter()
.map(|elf| {
elf.split_whitespace()
.map(|food| food.parse::<usize>().unwrap())
.sum()
})
.collect::<Vec<usize>>();
elves_calories.sort_by(|l, r| r.cmp(l));
elves_calories[..3].iter().sum::<usize>()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1() {
let input = "1000
2000
3000
4000
5000
6000
7000
8000
9000
10000";
assert_eq!(part1(input), 24000);
}
#[test]
fn test_2() {
let input = "1000
2000
3000
4000
5000
6000
7000
8000
9000
10000";
assert_eq!(part2(input), 45000);
}
}