[rs] Solve 2022_03 part 2
This commit is contained in:
parent
2bb6ed03fe
commit
afb6630869
1 changed files with 34 additions and 16 deletions
|
|
@ -1,30 +1,48 @@
|
||||||
use std::collections::HashSet;
|
fn parse_item(c: char) -> u64 {
|
||||||
|
let n = match c {
|
||||||
fn score(c: char) -> u32 {
|
'a'..='z' => c as u64 - 'a' as u64,
|
||||||
match c {
|
'A'..='Z' => c as u64 - 'A' as u64 + 26,
|
||||||
'a'..='z' => c as u32 - 'a' as u32 + 1,
|
|
||||||
'A'..='Z' => c as u32 - 'A' as u32 + 27,
|
|
||||||
_ => panic!(),
|
_ => panic!(),
|
||||||
|
};
|
||||||
|
1 << n
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn parse_items(s: &str) -> u64 {
|
||||||
|
s.chars().map(parse_item).reduce(|a, b| a | b).unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns the score of the item with the highest score
|
||||||
|
fn calc_score(i: u64) -> u32 {
|
||||||
|
64 - i.leading_zeros()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn solve(input: String) -> anyhow::Result<()> {
|
pub fn solve(input: String) -> anyhow::Result<()> {
|
||||||
let backpacks = input
|
let backpacks = input.lines().map(|l| l.trim()).collect::<Vec<_>>();
|
||||||
.lines()
|
|
||||||
.map(|l| l.trim())
|
|
||||||
.map(|l| l.split_at(l.len() / 2))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
// Part 1
|
// Part 1
|
||||||
let score = backpacks
|
let score = backpacks
|
||||||
.iter()
|
.iter()
|
||||||
.map(|(l, r)| {
|
.map(|backpack| {
|
||||||
let l = l.chars().collect::<HashSet<_>>();
|
let (l, r) = backpack.split_at(backpack.len() / 2);
|
||||||
let r = r.chars().collect::<HashSet<_>>();
|
calc_score(parse_items(l) & parse_items(r))
|
||||||
l.intersection(&r).map(|c| score(*c)).sum::<u32>()
|
|
||||||
})
|
})
|
||||||
.sum::<u32>();
|
.sum::<u32>();
|
||||||
println!("Part 1: {score}");
|
println!("Part 1: {score}");
|
||||||
|
|
||||||
|
// Part 2
|
||||||
|
let score = backpacks
|
||||||
|
.chunks(3)
|
||||||
|
.map(|chunk| {
|
||||||
|
calc_score(
|
||||||
|
chunk
|
||||||
|
.iter()
|
||||||
|
.map(|i| parse_items(i))
|
||||||
|
.reduce(|a, b| a & b)
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.sum::<u32>();
|
||||||
|
println!("Part 2: {score}");
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue