Last active
December 6, 2020 19:02
-
-
Save cranderveldt/ac78bedfc6cda289c0c690266a6bacf7 to your computer and use it in GitHub Desktop.
Advent of Code Day 4
This file contains 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
const puzzleInput = `` | |
// Part 1 | |
const parseInput = (input) => { | |
return input.replace(/\s/gi, '\n').split('\n\n') | |
} | |
const validateSurfaceFields = passport => { | |
const fields = passport.split('\n').map(field => field.substr(0, 3)) | |
return fields.length === 8 || (fields.length === 7 && !fields.includes('cid')) | |
} | |
const partOne = (input) => { | |
const passports = parseInput(input) | |
const validCount = passports.reduce((acc, passport) => acc + +validateSurfaceFields(passport), 0) | |
console.log(validCount) | |
} | |
partOne(puzzleInput) | |
// Part 2 | |
const validateField = (field) => { | |
const [key, value] = field.split(':') | |
const num = parseInt(value) | |
switch (key) { | |
case 'byr': return !!num && num >= 1920 && num <= 2002 | |
case 'iyr': return !!num && num >= 2010 && num <= 2020 | |
case 'eyr': return !!num && num >= 2020 && num <= 2030 | |
case 'hgt': { | |
if (value.endsWith('in')) { | |
return !!num && num >= 59 && num <= 76 | |
} | |
if (value.endsWith('cm')) { | |
return !!num && num >= 150 && num <= 193 | |
} | |
return false | |
} | |
case 'hcl': return !!value.match(/^#[0-9a-f]{6}$/) | |
case 'ecl': return !!value.match(/^(amb|blu|brn|gry|grn|hzl|oth)$/gi) | |
case 'pid': return !!value.match(/^\d{9}$/gi) | |
case 'cid': return true | |
default: return false | |
} | |
} | |
const validateDeepFields = passport => { | |
const fields = passport.split('\n') | |
const keys = fields.map(field => field.substr(0, 3)) | |
const correctFieldCount = keys.length === 8 || (keys.length === 7 && !keys.includes('cid')) | |
return correctFieldCount && fields.reduce((acc, field) => acc && validateField(field), true) | |
} | |
const partTwo = (input) => { | |
const passports = parseInput(input) | |
const validCount = passports.reduce((acc, passport) => acc + +validateDeepFields(passport), 0) | |
console.log(validCount) | |
} | |
partTwo(puzzleInput) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment