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