From 9d85ca0ee539cffe79e8c9864a929c168515c944 Mon Sep 17 00:00:00 2001 From: Antoine Martin Date: Fri, 4 Dec 2020 15:29:11 +0100 Subject: [PATCH] 2020: day04: refacto number range check --- aoc2020/src/day04.rs | 38 +++++++++++++------------------------- 1 file changed, 13 insertions(+), 25 deletions(-) diff --git a/aoc2020/src/day04.rs b/aoc2020/src/day04.rs index b709db9..569d222 100644 --- a/aoc2020/src/day04.rs +++ b/aoc2020/src/day04.rs @@ -1,5 +1,6 @@ use std::collections::HashMap; use std::fmt::Write; +use std::ops::RangeInclusive; use std::str::FromStr; const INPUT: &str = include_str!("../input/day04.txt"); @@ -138,42 +139,22 @@ impl CompletePassport { } fn byr_valid(&self) -> bool { - if let Ok(res) = self.byr.parse::() { - res >= 1920 && res <= 2002 - } else { - false - } + is_number_in_range(&self.byr, 1920..=2002) } fn iyr_valid(&self) -> bool { - if let Ok(res) = self.iyr.parse::() { - res >= 2010 && res <= 2020 - } else { - false - } + is_number_in_range(&self.iyr, 2010..=2020) } fn eyr_valid(&self) -> bool { - if let Ok(res) = self.eyr.parse::() { - res >= 2020 && res <= 2030 - } else { - false - } + is_number_in_range(&self.eyr, 2020..=2030) } fn hgt_valid(&self) -> bool { if let Some(num) = self.hgt.strip_suffix("in") { - if let Ok(res) = num.parse::() { - res >= 59 && res <= 76 - } else { - false - } + is_number_in_range(&num, 59..=76) } else if let Some(num) = self.hgt.strip_suffix("cm") { - if let Ok(res) = num.parse::() { - res >= 150 && res <= 193 - } else { - false - } + is_number_in_range(&num, 150..=193) } else { false } @@ -202,6 +183,13 @@ impl CompletePassport { } } +fn is_number_in_range(s: &str, range: RangeInclusive) -> bool { + match s.parse() { + Ok(res) => range.contains(&res), + Err(_) => false, + } +} + #[cfg(test)] mod tests { use super::*;