From 69fe736ff0547df3b64c4a3cc9b7da05b8d3f64b Mon Sep 17 00:00:00 2001 From: pjht Date: Sat, 3 Dec 2022 08:14:04 -0600 Subject: [PATCH] Rewrite day 3 to use Iterator::find --- src/day03.rs | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/src/day03.rs b/src/day03.rs index 0f2e913..3a9229d 100644 --- a/src/day03.rs +++ b/src/day03.rs @@ -16,12 +16,11 @@ pub struct NoCommonItem; impl Rucksack { fn find_item_in_both_halves(&self) -> Result { - 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 { - 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) } }