Skip to content

Instantly share code, notes, and snippets.

@kimagure44
Created December 4, 2020 15:54
Show Gist options
  • Save kimagure44/d9544ad172b66384d8990452f24c68a5 to your computer and use it in GitHub Desktop.
Save kimagure44/d9544ad172b66384d8990452f24c68a5 to your computer and use it in GitHub Desktop.
Advent of code (2020) - CODE 4 - 2
(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