Complete day 4.2
This commit is contained in:
parent
157f260d8f
commit
735089ad42
|
@ -17,7 +17,9 @@ fn parse_passports(input: &str) -> Result<Vec<HashMap<&str, &str>>, &str> {
|
||||||
.trim()
|
.trim()
|
||||||
.split(|c| c == ' ' || c == '\n')
|
.split(|c| c == ' ' || c == '\n')
|
||||||
.map(|field| {
|
.map(|field| {
|
||||||
let item = field.split_at(3);
|
let split = field.find(':').ok_or("Invalid passport entry; no separator")?;
|
||||||
|
let item = field.split_at(split);
|
||||||
|
|
||||||
let key = item.0;
|
let key = item.0;
|
||||||
let value = item
|
let value = item
|
||||||
.1
|
.1
|
||||||
|
@ -33,13 +35,55 @@ fn parse_passports(input: &str) -> Result<Vec<HashMap<&str, &str>>, &str> {
|
||||||
|
|
||||||
fn validate_passports(passports: &Vec<HashMap<&str, &str>>) -> usize {
|
fn validate_passports(passports: &Vec<HashMap<&str, &str>>) -> usize {
|
||||||
let required_fields = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"];
|
let required_fields = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"];
|
||||||
|
let rules = [
|
||||||
|
|year: &str| match year.parse() {
|
||||||
|
Ok(1920..=2002) => true,
|
||||||
|
_ => false,
|
||||||
|
},
|
||||||
|
|year: &str| match year.parse() {
|
||||||
|
Ok(2010..=2020) => true,
|
||||||
|
_ => false,
|
||||||
|
},
|
||||||
|
|year: &str| match year.parse() {
|
||||||
|
Ok(2020..=2030) => true,
|
||||||
|
_ => false,
|
||||||
|
},
|
||||||
|
|height: &str| match height.split_at(height.chars().count() - 2) {
|
||||||
|
(height, "cm") => match height.parse() {
|
||||||
|
Ok(150..=193) => true,
|
||||||
|
_ => false,
|
||||||
|
},
|
||||||
|
(height, "in") => match height.parse() {
|
||||||
|
Ok(59..=76) => true,
|
||||||
|
_ => false,
|
||||||
|
},
|
||||||
|
_ => false,
|
||||||
|
},
|
||||||
|
|color: &str| match color.split_at(1) {
|
||||||
|
("#", code) => code.chars().all(|a| char::is_ascii_hexdigit(&a)),
|
||||||
|
_ => false,
|
||||||
|
},
|
||||||
|
|color: &str| {
|
||||||
|
["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]
|
||||||
|
.iter()
|
||||||
|
.any(|c| c == &color)
|
||||||
|
},
|
||||||
|
|pid: &str| pid.chars().count() == 9 && pid.chars().all(char::is_numeric),
|
||||||
|
];
|
||||||
|
|
||||||
passports
|
passports
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|passport| {
|
.filter(|passport| {
|
||||||
required_fields
|
required_fields
|
||||||
.iter()
|
.iter()
|
||||||
.all(|field| passport.contains_key(field))
|
.zip(rules.iter())
|
||||||
|
.all(|(field, rule)| {
|
||||||
|
if let Some(value) = passport.get(field) {
|
||||||
|
rule(value)
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
})
|
||||||
})
|
})
|
||||||
.count()
|
.count()
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue