2022 day3/rust: cleanup
This commit is contained in:
parent
5ad4f56771
commit
c4268a0093
1 changed files with 36 additions and 22 deletions
|
@ -7,38 +7,52 @@ fn item_priority(item: char) -> u32 {
|
||||||
match item {
|
match item {
|
||||||
'a'..='z' => item as u32 - 'a' as u32 + 1,
|
'a'..='z' => item as u32 - 'a' as u32 + 1,
|
||||||
'A'..='Z' => item as u32 - 'A' as u32 + 27,
|
'A'..='Z' => item as u32 - 'A' as u32 + 27,
|
||||||
_ => unreachable!(),
|
_ => panic!("invalid item {item}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct Rucksack {
|
||||||
|
left: HashSet<char>,
|
||||||
|
right: HashSet<char>,
|
||||||
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let mut data = String::new();
|
let mut data = String::new();
|
||||||
stdin().read_to_string(&mut data).unwrap();
|
stdin().read_to_string(&mut data).unwrap();
|
||||||
|
|
||||||
let mut sum = 0;
|
let sacks: Vec<_> = data
|
||||||
for line in data.lines() {
|
.lines()
|
||||||
|
.map(|line| {
|
||||||
let (left, right) = line.split_at(line.len() / 2);
|
let (left, right) = line.split_at(line.len() / 2);
|
||||||
assert_eq!(left.len(), right.len());
|
assert_eq!(left.len(), right.len());
|
||||||
|
|
||||||
let left: HashSet<_> = left.chars().collect();
|
let left: HashSet<_> = left.chars().collect();
|
||||||
let right: HashSet<_> = right.chars().collect();
|
let right: HashSet<_> = right.chars().collect();
|
||||||
|
|
||||||
let common = *left.intersection(&right).next().unwrap();
|
Rucksack { left, right }
|
||||||
sum += item_priority(common);
|
})
|
||||||
}
|
.collect();
|
||||||
|
|
||||||
println!("{}", sum);
|
let sum1: u32 = sacks
|
||||||
|
|
||||||
let mut sum = 0;
|
|
||||||
for lines in data.lines().collect::<Vec<_>>().chunks(3) {
|
|
||||||
let common = lines
|
|
||||||
.iter()
|
.iter()
|
||||||
.map(|line| line.chars().collect::<HashSet<_>>())
|
.map(|sack| item_priority(*sack.left.intersection(&sack.right).next().unwrap()))
|
||||||
.reduce(|l, r| &l & &r)
|
.sum();
|
||||||
|
|
||||||
|
let sum2: u32 = sacks
|
||||||
|
.chunks(3)
|
||||||
|
.into_iter()
|
||||||
|
.map(|sacks| {
|
||||||
|
let common = sacks
|
||||||
|
.iter()
|
||||||
|
.map(|sack| &sack.left | &sack.right)
|
||||||
|
.reduce(|a, b| &a & &b)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(common.len(), 1);
|
assert_eq!(common.len(), 1);
|
||||||
|
|
||||||
sum += item_priority(common.into_iter().next().unwrap());
|
item_priority(common.into_iter().next().unwrap())
|
||||||
}
|
})
|
||||||
println!("{}", sum);
|
.sum();
|
||||||
|
|
||||||
|
println!("{}", sum1);
|
||||||
|
println!("{}", sum2);
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue