2020: day04: refacto number range check

This commit is contained in:
Antoine Martin 2020-12-04 15:29:11 +01:00
parent 3240ded93a
commit 9d85ca0ee5

View file

@ -1,5 +1,6 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::fmt::Write; use std::fmt::Write;
use std::ops::RangeInclusive;
use std::str::FromStr; use std::str::FromStr;
const INPUT: &str = include_str!("../input/day04.txt"); const INPUT: &str = include_str!("../input/day04.txt");
@ -138,42 +139,22 @@ impl CompletePassport {
} }
fn byr_valid(&self) -> bool { fn byr_valid(&self) -> bool {
if let Ok(res) = self.byr.parse::<i64>() { is_number_in_range(&self.byr, 1920..=2002)
res >= 1920 && res <= 2002
} else {
false
}
} }
fn iyr_valid(&self) -> bool { fn iyr_valid(&self) -> bool {
if let Ok(res) = self.iyr.parse::<i64>() { is_number_in_range(&self.iyr, 2010..=2020)
res >= 2010 && res <= 2020
} else {
false
}
} }
fn eyr_valid(&self) -> bool { fn eyr_valid(&self) -> bool {
if let Ok(res) = self.eyr.parse::<i64>() { is_number_in_range(&self.eyr, 2020..=2030)
res >= 2020 && res <= 2030
} else {
false
}
} }
fn hgt_valid(&self) -> bool { fn hgt_valid(&self) -> bool {
if let Some(num) = self.hgt.strip_suffix("in") { if let Some(num) = self.hgt.strip_suffix("in") {
if let Ok(res) = num.parse::<i64>() { is_number_in_range(&num, 59..=76)
res >= 59 && res <= 76
} else {
false
}
} else if let Some(num) = self.hgt.strip_suffix("cm") { } else if let Some(num) = self.hgt.strip_suffix("cm") {
if let Ok(res) = num.parse::<i64>() { is_number_in_range(&num, 150..=193)
res >= 150 && res <= 193
} else {
false
}
} else { } else {
false false
} }
@ -202,6 +183,13 @@ impl CompletePassport {
} }
} }
fn is_number_in_range(s: &str, range: RangeInclusive<i64>) -> bool {
match s.parse() {
Ok(res) => range.contains(&res),
Err(_) => false,
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;