day(03): make helper functions
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
c96bab1a71
commit
35ea8ccb22
1 changed files with 23 additions and 14 deletions
|
@ -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 {
|
||||
input
|
||||
.iter()
|
||||
.map(|Backpack(left, right)| left.intersection(right).sum::<i32>())
|
||||
.map(|b| b.common_items().iter().sum::<i32>())
|
||||
.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 {
|
||||
input
|
||||
.iter()
|
||||
.map(|Backpack(left, right)| left.union(right).cloned().collect())
|
||||
.collect::<Vec<HashSet<i32>>>()
|
||||
.chunks(3)
|
||||
.map(|sets| {
|
||||
// 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)
|
||||
})
|
||||
.map(|backpacks| common_items(backpacks).iter().sum::<i32>())
|
||||
.sum()
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue