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()
|
||||||
let (left, right) = line.split_at(line.len() / 2);
|
.map(|line| {
|
||||||
assert_eq!(left.len(), right.len());
|
let (left, right) = line.split_at(line.len() / 2);
|
||||||
|
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
|
||||||
|
.iter()
|
||||||
|
.map(|sack| item_priority(*sack.left.intersection(&sack.right).next().unwrap()))
|
||||||
|
.sum();
|
||||||
|
|
||||||
let mut sum = 0;
|
let sum2: u32 = sacks
|
||||||
for lines in data.lines().collect::<Vec<_>>().chunks(3) {
|
.chunks(3)
|
||||||
let common = lines
|
.into_iter()
|
||||||
.iter()
|
.map(|sacks| {
|
||||||
.map(|line| line.chars().collect::<HashSet<_>>())
|
let common = sacks
|
||||||
.reduce(|l, r| &l & &r)
|
.iter()
|
||||||
.unwrap();
|
.map(|sack| &sack.left | &sack.right)
|
||||||
assert_eq!(common.len(), 1);
|
.reduce(|a, b| &a & &b)
|
||||||
|
.unwrap();
|
||||||
|
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