[rs] Simplify 2022_03

This commit is contained in:
Joscha 2022-12-03 13:02:57 +01:00
parent afb6630869
commit 6dc0aef430

View file

@ -1,10 +1,9 @@
fn parse_item(c: char) -> u64 { fn parse_item(c: char) -> u64 {
let n = match c { 1 << match c {
'a'..='z' => c as u64 - 'a' as u64, 'a'..='z' => c as u64 - 'a' as u64,
'A'..='Z' => c as u64 - 'A' as u64 + 26, 'A'..='Z' => c as u64 - 'A' as u64 + 26,
_ => panic!(), _ => panic!(),
}; }
1 << n
} }
fn parse_items(s: &str) -> u64 { fn parse_items(s: &str) -> u64 {
@ -12,7 +11,7 @@ fn parse_items(s: &str) -> u64 {
} }
// Returns the score of the item with the highest score // Returns the score of the item with the highest score
fn calc_score(i: u64) -> u32 { fn highest_score(i: u64) -> u32 {
64 - i.leading_zeros() 64 - i.leading_zeros()
} }
@ -24,7 +23,7 @@ pub fn solve(input: String) -> anyhow::Result<()> {
.iter() .iter()
.map(|backpack| { .map(|backpack| {
let (l, r) = backpack.split_at(backpack.len() / 2); let (l, r) = backpack.split_at(backpack.len() / 2);
calc_score(parse_items(l) & parse_items(r)) highest_score(parse_items(l) & parse_items(r))
}) })
.sum::<u32>(); .sum::<u32>();
println!("Part 1: {score}"); println!("Part 1: {score}");
@ -32,15 +31,13 @@ pub fn solve(input: String) -> anyhow::Result<()> {
// Part 2 // Part 2
let score = backpacks let score = backpacks
.chunks(3) .chunks(3)
.map(|chunk| { .map(|c| {
calc_score( c.iter()
chunk .map(|i| parse_items(i))
.iter() .reduce(|a, b| a & b)
.map(|i| parse_items(i)) .unwrap()
.reduce(|a, b| a & b)
.unwrap(),
)
}) })
.map(highest_score)
.sum::<u32>(); .sum::<u32>();
println!("Part 2: {score}"); println!("Part 2: {score}");