r/backtickbot • u/backtickbot • Dec 04 '20
https://np.reddit.com/r/adventofcode/comments/k6e8sw/2020_day_04_solutions/gembo0v/
My solution in Rust:
use aoc_runner_derive::{aoc, aoc_generator};
use regex::Regex;
#[aoc_generator(day4)]
pub fn input_generator(input: &str) -> Vec<String> {
input.split("\n\n").map(|x| x.replace("\n", " ")).collect()
}
#[aoc(day4, part1)]
pub fn solve_first(input: &Vec<String>) -> usize {
input.iter().filter(|&x| validate_fields(x)).count()
}
fn validate_fields(input: &str) -> bool {
input.contains("byr:")
&& input.contains("iyr:")
&& input.contains("eyr:")
&& input.contains("hgt:")
&& input.contains("hcl:")
&& input.contains("ecl:")
&& input.contains("pid:")
}
fn check_year(input: &str, lower: usize, upper: usize) -> bool {
let year = input.parse().unwrap();
lower <= year && year <= upper
}
fn check_hgt(input: &str) -> bool {
let val: usize = input[0..input.len() - 2].parse().unwrap_or(0);
let unit: &str = &input[input.len() - 2..input.len()];
if unit == "cm" {
return 150 <= val && val <= 193;
}
if unit == "in" {
return 59 <= val && val <= 76;
}
false
}
fn check_hcl(input: &str) -> bool {
let re = Regex::new(r"#[a-f\d]{6}").unwrap();
re.is_match(input)
}
fn check_ecl(input: &str) -> bool {
input == "blu"
|| input == "amb"
|| input == "brn"
|| input == "gry"
|| input == "grn"
|| input == "hzl"
|| input == "oth"
}
fn check_pid(input: &str) -> bool {
let re = Regex::new(r"\d{9}").unwrap();
re.is_match(input) && input.len() == 9
}
fn check_value(input: &str) -> bool {
let items: Vec<_> = input.split(":").collect();
match items[0] {
"byr" => return check_year(items[1], 1920, 2002),
"iyr" => return check_year(items[1], 2010, 2020),
"eyr" => return check_year(items[1], 2020, 2030),
"hgt" => return check_hgt(items[1]),
"hcl" => return check_hcl(items[1]),
"ecl" => return check_ecl(items[1]),
"pid" => return check_pid(items[1]),
"cid" => return true,
_ => panic!("Unknown Field"),
}
unreachable!()
}
#[aoc(day4, part2)]
pub fn solve_second(input: &Vec<String>) -> usize {
let check_all_values = |passport: &String| passport.split(" ").all(|p| check_value(p));
input
.iter()
.filter(|&x| validate_fields(x))
.filter(|&x| check_all_values(x))
.count()
}
1
Upvotes