Created
December 4, 2020 15:54
-
-
Save kimagure44/d9544ad172b66384d8990452f24c68a5 to your computer and use it in GitHub Desktop.
Advent of code (2020) - CODE 4 - 2
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
(async () => { | |
const fn = item => { | |
const { | |
byr = null, | |
ecl = null, | |
eyr = null, | |
hcl = null, | |
hgt = null, | |
iyr = null, | |
pid = null | |
} = Object.fromEntries(item.map(i => i.split(':'))); | |
const validBYR = byr.length === 4 && parseInt(byr) >= 1920 && parseInt(byr) <= 2002; | |
const validIYR = iyr.length === 4 && parseInt(iyr) >= 2010 && parseInt(iyr) <= 2020; | |
const validEYR = eyr.length === 4 && parseInt(eyr) >= 2020 && parseInt(eyr) <= 2030; | |
const validHGT = hgt.includes('cm') ? parseInt(hgt) >= 150 && parseInt(hgt) <= 193 : parseInt(hgt) >= 59 && parseInt(hgt) <= 76; | |
const validHCL = /#(?:[a-f0-9]{6})\b|\([^\)]*\)/gi.test(hcl); | |
const validECL = ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'].some(item => item.includes(ecl)); | |
const validPID = pid.length === 9; | |
return validBYR && validIYR && validEYR && validHGT && validHCL && validECL && validPID; | |
}; | |
const result = []; | |
let t = []; | |
let validPassport = 0; | |
const passportStruct = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']; // cid opcional | |
const entries = (await(await fetch('https://adventofcode.com/2020/day/4/input')).text()).split('\n').map(item => { | |
if (item) { | |
t.push(item); | |
} else { | |
item = t.slice(); | |
t = []; | |
return item; | |
} | |
}).filter(item => item).map(item => item.map(el => el.split(' ')).flat()); | |
entries.forEach(item => { | |
if (item.length === 8) { | |
if (fn(item)) { | |
validPassport++; | |
} | |
} | |
if (item.length === 7) { | |
const isValid = !item.some(el => el.includes('cid')); | |
if (isValid) { | |
if (fn(item)) { | |
validPassport++; | |
} | |
} | |
} | |
}); | |
const startTime = performance.now(); | |
const endTime = performance.now(); | |
console.log(`Pasaportes válidos: ${validPassport}`, `${parseFloat(endTime - startTime).toFixed(4)} ms`); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment