day4: simplify part2

This commit is contained in:
Johannes Loher 2020-12-04 12:32:58 +01:00
parent d63da28b74
commit 8c2798e26b

View file

@ -17,31 +17,6 @@ auto parsePassports(string input)
}).assocArray); }).assocArray);
} }
enum Field : string
{
birthYear = "byr",
issueYear = "iyr",
expirationYear = "eyr",
height = "hgt",
hairColor = "hcl",
eyeColor = "ecl",
passportID = "pid",
countryID = "cid",
}
bool isValidYear(int min, int max)(string yr)
{
if (yr.length != 4 || yr.canFind!(not!isDigit))
return false;
auto year = yr.to!int;
return year >= min && year <= max;
}
alias isValidBirthYear = isValidYear!(1920, 2002);
alias isValidIssueYear = isValidYear!(2010, 2020);
alias isValidExpirationYear = isValidYear!(2020, 2030);
bool isValidHeight(string hgt) bool isValidHeight(string hgt)
{ {
auto match = hgt.matchFirst(r"^(\d+)(cm|in)$"); auto match = hgt.matchFirst(r"^(\d+)(cm|in)$");
@ -61,36 +36,24 @@ bool isValidHeight(string hgt)
} }
} }
bool isValidHairColor(string hcl) alias isBetween = (x, min, max) => x >= min && x <= max;
{
return hcl.matchFirst(r"^#[0-9a-f]{6}$").to!bool;
}
bool isValidEyeColor(string ecl)
{
return ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"].canFind(ecl);
}
bool isValidPassportID(string pid)
{
return pid.matchFirst(r"^\d{9}$").to!bool;
}
enum requiredFields = [
Field.birthYear, Field.issueYear, Field.expirationYear, Field.height,
Field.hairColor, Field.eyeColor, Field.passportID
];
bool isValidPassport(Passport passport) bool isValidPassport(Passport passport)
{ {
return requiredFields.all!(field => field in passport) // dfmt off
&& isValidBirthYear(passport[Field.birthYear]) auto validators = [
&& isValidIssueYear(passport[Field.issueYear]) "byr" : s => s.length == 4 && s.all!isDigit && s.to!int.isBetween(1920, 2002),
&& isValidExpirationYear(passport[Field.expirationYear]) "iyr" : s => s.length == 4 && s.all!isDigit && s.to!int.isBetween(2010, 2020),
&& isValidHeight(passport[Field.height]) "eyr" : s => s.length == 4 && s.all!isDigit && s.to!int.isBetween(2020, 2030),
&& isValidHairColor(passport[Field.hairColor]) "hgt" : &isValidHeight,
&& isValidEyeColor(passport[Field.eyeColor]) "hcl" : s => s.matchFirst(r"^#[0-9a-f]{6}$").to!bool,
&& isValidPassportID(passport[Field.passportID]); "ecl" : s => [ "amb", "blu", "brn", "gry", "grn", "hzl", "oth" ].canFind(s),
"pid" : s => s.matchFirst(r"^\d{9}$").to!bool
];
// dfmt on
return validators.byKeyValue.all!(validator => validator.key in passport
&& validator.value()(passport[validator.key]));
} }
auto countValidPassports(R)(R r) if (isInputRange!R && is(ElementType!R == Passport)) auto countValidPassports(R)(R r) if (isInputRange!R && is(ElementType!R == Passport))