Rust Day 1

This commit is contained in:
Tobias Berger 2022-12-01 10:49:53 +01:00
parent 14abcd622e
commit 19559cea15
Signed by: toby
GPG key ID: 2D05EFAB764D6A88
6 changed files with 2305 additions and 3 deletions

2
rust/Cargo.lock generated
View file

@ -4,4 +4,4 @@ version = 3
[[package]] [[package]]
name = "advent-of-code" name = "advent-of-code"
version = "22.0.2" version = "22.1.2"

View file

@ -1,6 +1,6 @@
[package] [package]
name = "advent-of-code" name = "advent-of-code"
version = "22.0.2" version = "22.1.2"
edition = "2021" edition = "2021"
resolver = "2" resolver = "2"
@ -26,3 +26,7 @@ codegen-units = 1
[[bin]] [[bin]]
name = "day00" name = "day00"
path = "src/day00/main.rs" path = "src/day00/main.rs"
[[bin]]
name = "day01"
path = "src/day01/main.rs"

2251
rust/src/day01/input.txt Normal file

File diff suppressed because it is too large Load diff

11
rust/src/day01/main.rs Normal file
View file

@ -0,0 +1,11 @@
const INPUT: &str = include_str!("input.txt");
mod part_1;
use part_1::part_1;
mod part_2;
use part_2::part_2;
pub fn main() {
part_1(INPUT);
part_2(INPUT);
}

17
rust/src/day01/part_1.rs Normal file
View file

@ -0,0 +1,17 @@
pub(crate) fn part_1(input: &'static str) {
let maximum = input
.split("\n\n")
.map(|inventory| {
inventory
.split('\n')
.map(|item| {
item.parse::<u32>()
.expect("Input isn't clean. Non-number found")
})
.sum::<u32>()
})
.max()
.expect("No highest inventory found. Input unclean?");
println!("Part 1: {maximum}")
}

19
rust/src/day01/part_2.rs Normal file
View file

@ -0,0 +1,19 @@
pub(crate) fn part_2(input: &'static str) {
let mut calories = input
.split("\n\n")
.map(|inventory| {
inventory
.split('\n')
.map(|item| {
item.parse::<u32>()
.expect("Input isn't clean. Non-number found")
})
.sum::<u32>()
})
.collect::<Vec<_>>();
calories.sort();
calories.reverse();
let top_three = calories.iter().take(3).sum::<u32>();
println!("Part 2: {top_three}");
}