diff options
| author | Jan Tuomi <jans.tuomi@gmail.com> | 2020-12-04 11:41:58 +0200 |
|---|---|---|
| committer | Jan Tuomi <jans.tuomi@gmail.com> | 2020-12-04 11:41:58 +0200 |
| commit | 8715b00668e7811b31238eca7045e7d0c00a37ef (patch) | |
| tree | 9287301e28f92aae94931f1cb9b050047879c347 /day4/index.ts | |
| parent | 2a09118fcd1ebb62413291f1a0ec973339b73ed6 (diff) | |
Solve 4.2
Diffstat (limited to 'day4/index.ts')
| -rw-r--r-- | day4/index.ts | 56 |
1 files changed, 54 insertions, 2 deletions
diff --git a/day4/index.ts b/day4/index.ts index 1d059dc..2ee8775 100644 --- a/day4/index.ts +++ b/day4/index.ts @@ -26,7 +26,7 @@ const parsePassports = (input: string): Passport[] => { return result; } -const isPassportValid = (passport: Passport): boolean => { +const requiredFieldsPresent = (passport: Passport): boolean => { const requiredKeys = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]; let valid = true; @@ -38,15 +38,67 @@ const isPassportValid = (passport: Passport): boolean => { return valid; } +const byrValid = (byr: string): boolean => { + const match = byr.match(/\d{4}/); + if (!match) return false; + const val = Number(match[0]); + return val >= 1920 && val <= 2002; +} + +const iyrValid = (iyr: string): boolean => { + const match = iyr.match(/\d{4}/); + if (!match) return false; + const val = Number(match[0]); + return val >= 2010 && val <= 2020; +} + +const eyrValid = (eyr: string): boolean => { + const match = eyr.match(/\d{4}/); + if (!match) return false; + const val = Number(match[0]); + return val >= 2020 && val <= 2030; +} + +const hgtValid = (hgt: string): boolean => { + const match = hgt.match(/(\d{2,3})(cm|in)/); + if (!match) return false; + const val = Number(match[1]); + const unit = match[2]; + return (unit === "cm" && val >= 150 && val <= 193) || (unit === "in" && val >= 59 && val <= 76); +} + +const hclValid = (hcl: string): boolean => !!hcl.match(/\#[0-9a-f]{6}/); + +const eclValid = (ecl: string): boolean => ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"].includes(ecl); + +const pidValid = (pid: string): boolean => !!pid.match(/\d{9}/); + +const isPassportValid = (passport: Passport): boolean => + requiredFieldsPresent(passport) + && byrValid(passport.byr) + && iyrValid(passport.iyr) + && eyrValid(passport.eyr) + && hgtValid(passport.hgt) + && hclValid(passport.hcl) + && eclValid(passport.ecl) + && pidValid(passport.pid) + const day4: ExerciseModuleFunc = async (input: string) => { const prom1 = of(input).pipe( map(parsePassports), concatAll(), + filter(requiredFieldsPresent), + count() + ).toPromise(); + + const prom2 = of(input).pipe( + map(parsePassports), + concatAll(), filter(isPassportValid), count() ).toPromise(); - return Promise.all([prom1]); + return Promise.all([prom1, prom2]); } export default day4; |
