Browse Source

clean up validators for day 4 part 2 a little bit

main
Colin McMillen 3 years ago
parent
commit
5d822ff397
  1. 48
      2020/Day04.cs

48
2020/Day04.cs

@ -38,6 +38,27 @@ namespace AdventOfCode {
return result;
}
static bool ValidateYear(string value, int min, int max) {
int year = ParseInt(value);
return year >= min && year <= max;
}
static bool ValidateHeight(string value) {
string unit = value.Substring(value.Length - 2);
int amount = ParseInt(value.Substring(0, value.Length - 2));
if (unit == "cm") {
return amount >= 150 && amount <= 193;
} else if (unit == "in") {
return amount >= 59 && amount <= 76;
} else { // not cm or in
return false;
}
}
static bool ValidateHairColor(string value) {
return Regex.IsMatch(value, @"^#[0-9a-f]{6}$");
}
static bool IsValidPassport2(string input) {
string[] fields = input.Split(' ');
var fieldsPresent = new HashSet<string>();
@ -50,37 +71,23 @@ namespace AdventOfCode {
string value = tokens[1];
fieldsPresent.Add(key);
if (key == "byr") {
int year = ParseInt(value);
if (year < 1920 || year > 2002) {
if (!ValidateYear(value, 1920, 2002)) {
return false;
}
} else if (key == "iyr") {
int year = ParseInt(value);
if (year < 2010 || year > 2020) {
if (!ValidateYear(value, 2010, 2020)) {
return false;
}
} else if (key == "eyr") {
int year = ParseInt(value);
if (year < 2020 || year > 2030) {
if (!ValidateYear(value, 2020, 2030)) {
return false;
}
} else if (key == "hgt") {
string unit = value.Substring(value.Length - 2);
int amount = ParseInt(value.Substring(0, value.Length - 2));
if (unit == "cm") {
if (amount < 150 || amount > 193) {
return false;
}
} else if (unit == "in") {
if (amount < 59 || amount > 76) {
return false;
}
} else { // not cm or in
if (!ValidateHeight(value)) {
return false;
}
} else if (key == "hcl") {
Regex color = new Regex(@"^#[0-9a-f]{6}$");
if (!color.IsMatch(value)) {
if (!ValidateHairColor(value)) {
return false;
}
} else if (key == "ecl") {
@ -88,8 +95,7 @@ namespace AdventOfCode {
return false;
}
} else if (key == "pid") {
Regex pid = new Regex(@"^[0-9]{9}$");
if (!pid.IsMatch(value)) {
if (!Regex.IsMatch(value, @"^[0-9]{9}$")) {
return false;
}
}

Loading…
Cancel
Save