Skip to content

Instantly share code, notes, and snippets.

@Friss
Created December 4, 2020 05:42
Show Gist options
  • Save Friss/d8bfb3df18addf6005b7d41a3d5af1a1 to your computer and use it in GitHub Desktop.
Save Friss/d8bfb3df18addf6005b7d41a3d5af1a1 to your computer and use it in GitHub Desktop.
const fs = require('fs').promises;
(async () => {
console.log(`Reading input from ${__dirname}/${process.argv[2]}.txt`);
const inputData = await fs.readFile(`${__dirname}/${process.argv[2]}.txt`);
const inputs = inputData.toString().split('\n\n');
const neededFields = [
{
string: 'byr',
length: 4,
isNum: true,
minRange: 1920,
maxRange: 2002,
},
{
string: 'iyr',
length: 4,
isNum: true,
minRange: 2010,
maxRange: 2020,
},
{
string: 'eyr',
length: 4,
isNum: true,
minRange: 2020,
maxRange: 2030,
},
{
string: 'hgt',
isNum: true,
},
{
string: 'hcl',
length: 7,
regex: /#[0-9a-f]{6}/,
},
{
string: 'ecl',
length: 3,
includesValue: ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'],
},
{
string: 'pid',
length: 9,
isNum: true,
regex: /[0-9]{9}/,
},
];
let firstCount = 0;
let secondCount = 0;
inputs.forEach((passport) => {
if (neededFields.every((field) => passport.includes(field.string))) {
firstCount++;
const fieldMap = {};
passport = passport
.replaceAll('\n', ' ')
.split(' ')
.map((field) => {
const [key, value] = field.split(':');
fieldMap[key] = value;
});
if (
neededFields.every((field) => {
const fieldValue = fieldMap[field.string];
if (field.length && fieldValue.length !== field.length) {
return false;
}
if (field.isNum && isNaN(parseInt(fieldValue, 10))) {
return false;
}
if (field.regex && !field.regex.test(fieldValue)) {
return false;
}
if (field.maxRange && parseInt(fieldValue) > field.maxRange) {
return false;
}
if (field.minRange && parseInt(fieldValue) < field.minRange) {
return false;
}
if (field.string === 'hgt') {
if (!(fieldValue.includes('cm') || fieldValue.includes('in'))) {
return false;
}
if (fieldValue.includes('cm')) {
const height = parseInt(fieldValue.replace('cm', ''), 10);
if (height > 193) {
return false;
}
if (height < 150) {
return false;
}
}
if (fieldValue.includes('in')) {
const height = parseInt(fieldValue.replace('in', ''), 10);
if (height < 59) {
return false;
}
if (height > 76) {
return false;
}
}
}
if (
field.includesValue &&
!field.includesValue.includes(fieldValue)
) {
return false;
}
return true;
})
) {
secondCount++;
}
}
});
console.log('firstCount', firstCount);
console.log('secondCount', secondCount);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment