Rewrite day 3 to use Iterator::find

This commit is contained in:
pjht 2022-12-03 08:14:04 -06:00
parent 838456f0e7
commit 69fe736ff0

View File

@ -16,12 +16,11 @@ pub struct NoCommonItem;
impl Rucksack { impl Rucksack {
fn find_item_in_both_halves(&self) -> Result<u8, NoItemInBothHalves> { fn find_item_in_both_halves(&self) -> Result<u8, NoItemInBothHalves> {
for &item in &self.first_half { self.first_half
if self.second_half.contains(&item) { .iter()
return Ok(item); .copied()
} .find(|item| self.second_half.contains(item))
} .ok_or(NoItemInBothHalves)
Err(NoItemInBothHalves)
} }
fn has_item(&self, item: u8) -> bool { fn has_item(&self, item: u8) -> bool {
@ -29,12 +28,12 @@ impl Rucksack {
} }
fn find_common_item(&self, others: &[Rucksack]) -> Result<u8, NoCommonItem> { fn find_common_item(&self, others: &[Rucksack]) -> Result<u8, NoCommonItem> {
for &item in self.first_half.iter().chain(&self.second_half) { self.first_half
if others.iter().all(|rucksack| rucksack.has_item(item)) { .iter()
return Ok(item); .chain(&self.second_half)
} .copied()
} .find(|&item| others.iter().all(|rucksack| rucksack.has_item(item)))
Err(NoCommonItem) .ok_or(NoCommonItem)
} }
} }