[rs] Solve 2022_03 part 1

This commit is contained in:
Joscha 2022-12-03 12:43:18 +01:00
parent daa1ee9183
commit 2bb6ed03fe
5 changed files with 339 additions and 0 deletions

View file

@ -39,6 +39,7 @@ impl Day {
days! {
Y2022D01: "2022_01",
Y2022D02: "2022_02",
Y2022D03: "2022_03",
}
#[derive(Parser)]
@ -73,6 +74,7 @@ fn main() -> anyhow::Result<()> {
match day {
Day::Y2022D01 => y2022::d01::solve(input)?,
Day::Y2022D02 => y2022::d02::solve(input)?,
Day::Y2022D03 => y2022::d03::solve(input)?,
}
}

View file

@ -1,2 +1,3 @@
pub mod d01;
pub mod d02;
pub mod d03;

30
rs/src/y2022/d03.rs Normal file
View file

@ -0,0 +1,30 @@
use std::collections::HashSet;
fn score(c: char) -> u32 {
match c {
'a'..='z' => c as u32 - 'a' as u32 + 1,
'A'..='Z' => c as u32 - 'A' as u32 + 27,
_ => panic!(),
}
}
pub fn solve(input: String) -> anyhow::Result<()> {
let backpacks = input
.lines()
.map(|l| l.trim())
.map(|l| l.split_at(l.len() / 2))
.collect::<Vec<_>>();
// Part 1
let score = backpacks
.iter()
.map(|(l, r)| {
let l = l.chars().collect::<HashSet<_>>();
let r = r.chars().collect::<HashSet<_>>();
l.intersection(&r).map(|c| score(*c)).sum::<u32>()
})
.sum::<u32>();
println!("Part 1: {score}");
Ok(())
}