1
0
Fork 0

day(03): make helper functions

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2022-12-03 14:51:26 +01:00
parent c96bab1a71
commit 35ea8ccb22
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -37,29 +37,38 @@ impl FromStr for Backpack {
} }
} }
impl Backpack {
fn common_items(&self) -> HashSet<i32> {
let Backpack(left, right) = self;
left.intersection(right).cloned().collect()
}
fn all_items(&self) -> HashSet<i32> {
let Backpack(left, right) = self;
left.union(right).cloned().collect()
}
}
fn part_1(input: &Input) -> Output { fn part_1(input: &Input) -> Output {
input input
.iter() .iter()
.map(|Backpack(left, right)| left.intersection(right).sum::<i32>()) .map(|b| b.common_items().iter().sum::<i32>())
.sum() .sum()
} }
fn common_items(backpacks: &[Backpack]) -> HashSet<i32> {
backpacks
.iter()
.skip(1)
.fold(backpacks[0].all_items(), |u, b| {
u.intersection(&b.all_items()).cloned().collect()
})
}
fn part_2(input: &Input) -> Output { fn part_2(input: &Input) -> Output {
input input
.iter()
.map(|Backpack(left, right)| left.union(right).cloned().collect())
.collect::<Vec<HashSet<i32>>>()
.chunks(3) .chunks(3)
.map(|sets| { .map(|backpacks| common_items(backpacks).iter().sum::<i32>())
// debug!("Sets: {:?}", sets);
sets.iter()
.skip(1)
.fold(sets[0].clone(), |acc, s| {
acc.intersection(s).cloned().collect()
})
.iter()
.fold(0, |acc, x| acc + *x)
})
.sum() .sum()
} }