advent-of-code/2022/day3/rust/src/main.rs

92 lines
2 KiB
Rust
Raw Normal View History

2022-12-03 06:16:52 +01:00
use std::{
io::{stdin, Read},
2022-12-03 06:46:00 +01:00
ops::{BitAnd, BitOr},
2022-12-03 06:16:52 +01:00
};
fn item_priority(item: char) -> u32 {
match item {
'a'..='z' => item as u32 - 'a' as u32 + 1,
'A'..='Z' => item as u32 - 'A' as u32 + 27,
2022-12-03 06:29:32 +01:00
_ => panic!("invalid item {item}"),
2022-12-03 06:16:52 +01:00
}
}
2022-12-03 06:46:00 +01:00
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ItemSet(u64);
impl ItemSet {
pub fn priority_of_single_item(self) -> Option<u32> {
if self.0.is_power_of_two() {
Some(self.0.trailing_zeros())
} else {
None
}
}
}
impl FromIterator<char> for ItemSet {
fn from_iter<T: IntoIterator<Item = char>>(iter: T) -> Self {
Self(
iter.into_iter()
.map(item_priority)
.fold(0, |acc, i| acc | (1 << i)),
)
}
}
impl BitOr for ItemSet {
type Output = Self;
fn bitor(self, rhs: Self) -> Self::Output {
Self(BitOr::bitor(self.0, rhs.0))
}
}
impl BitAnd for ItemSet {
type Output = Self;
fn bitand(self, rhs: Self) -> Self::Output {
Self(BitAnd::bitand(self.0, rhs.0))
}
}
2022-12-03 06:16:52 +01:00
fn main() {
let mut data = String::new();
stdin().read_to_string(&mut data).unwrap();
2022-12-03 06:29:32 +01:00
let sacks: Vec<_> = data
.lines()
.map(|line| {
let (left, right) = line.split_at(line.len() / 2);
assert_eq!(left.len(), right.len());
let left: ItemSet = left.chars().collect();
let right: ItemSet = right.chars().collect();
2022-12-03 06:29:32 +01:00
(left, right)
2022-12-03 06:29:32 +01:00
})
.collect();
let sum1: u32 = sacks
.iter()
.map(|&(left, right)| (left & right).priority_of_single_item().unwrap())
2022-12-03 06:29:32 +01:00
.sum();
let sum2: u32 = sacks
.chunks(3)
.into_iter()
.map(|sacks| {
2022-12-03 06:46:00 +01:00
sacks
2022-12-03 06:29:32 +01:00
.iter()
.map(|&(left, right)| left | right)
2022-12-03 06:46:00 +01:00
.reduce(BitAnd::bitand)
.unwrap()
.priority_of_single_item()
.unwrap()
2022-12-03 06:29:32 +01:00
})
.sum();
println!("{}", sum1);
println!("{}", sum2);
2022-12-03 06:16:52 +01:00
}