Created
January 24, 2022 09:59
-
-
Save neofight78/b1c5c97075019f876755a74843431714 to your computer and use it in GitHub Desktop.
Advent of Code 2020 - Day 4: Passport Processing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let part1 = count_valid_passports(INPUT, part1_filter); | |
let part2 = count_valid_passports(INPUT, part2_filter); | |
println!("Part 1: {}", part1); | |
println!("Part 2: {}", part2); | |
} | |
fn count_valid_passports(batch: &str, filter: fn(&str, &str) -> bool) -> usize { | |
batch | |
.split("\n\n") | |
.filter(|p| { | |
p.split_whitespace() | |
.map(|kv| kv.split_once(':').unwrap()) | |
.filter(|&(k, v)| k != "cid" && filter(k, v)) | |
.count() | |
== 7 | |
}) | |
.count() | |
} | |
fn part1_filter(_: &str, _: &str) -> bool { | |
true | |
} | |
fn part2_filter(key: &str, value: &str) -> bool { | |
match key { | |
"byr" => (1920..=2002).contains(&value.parse().unwrap()), | |
"iyr" => (2010..=2020).contains(&value.parse().unwrap()), | |
"eyr" => (2020..=2030).contains(&value.parse().unwrap()), | |
"hgt" => match &value[value.len() - 2..] { | |
"cm" if (150..=193).contains(&value[..value.len() - 2].parse().unwrap()) => true, | |
"in" if (59..=76).contains(&value[..value.len() - 2].parse().unwrap()) => true, | |
_ => false, | |
}, | |
"hcl" => { | |
value.len() == 7 | |
&& value.as_bytes()[0] == b'#' | |
&& usize::from_str_radix(&value[1..], 16).is_ok() | |
} | |
"ecl" => ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"].contains(&value), | |
"pid" => value.len() == 9 && value.parse::<usize>().is_ok(), | |
_ => panic!("Unrecognised field"), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment