Advent of Code, Day 4: Passport Processing
Go to Day 4 Challenge |
Go to index
I ran this code in the devtoolbar in Chrome, and the answers were simply outputted to the console.
Learn more about my solution.
Part I
"Passport data is validated in batch files (your puzzle input). Each passport is represented as a
sequence of key:value pairs separated by spaces or newlines. Passports are separated by blank lines...
Count the number of valid passports - those that have all required fields. Treat cid as optional. In your
batch file, how many passports are valid?"
ref
var data = window.document.getElementsByTagName("pre")[0].innerText
var transformPassports = data.replace(/\n\n/ig,'LOZZI')
var noNewLines = transformPassports.replace(/\n/ig, ' ')
var passports = noNewLines.split('LOZZI')
var counter = 0
passports.forEach(p => {
var fields = p.trim().split(' ')
if(fields.length === 8) {
counter++
} else if(fields.length === 7 && p.indexOf('cid') === -1){
counter ++
}
})
console.log(counter)
Part II
"You can continue to ignore the cid field, but each other field has strict rules about what values are
valid for automatic validation."
ref
var data = window.document.getElementsByTagName("pre")[0].innerText
var transformPassports = data.replace(/\n\n/ig,'LOZZI')
var noNewLines = transformPassports.replace(/\n/ig, ' ')
var passports = noNewLines.split('LOZZI')
var isValid = (field) => {
var pair = field.split(':')
var value = pair[1]
switch (pair[0]) {
case 'byr':
if(value.length !== 4) return false
if(Number(value) >= 1920 && Number(value) <= 2002) return true
break
case 'iyr':
if(value.length !== 4) return false
if(Number(value) >= 2010 && Number(value) <= 2020) return true
break
case 'eyr':
if(value.length !== 4) return false
if(Number(value) >= 2020 && Number(value) <= 2030) return true
break
case 'hgt':
var height = value.match(/([0-9]*)(cm|in)/)
if(height) {
var measurement = height[2]
var heightVal = height[1]
if(measurement === 'cm') {
if(Number(heightVal) >= 150 && Number(heightVal) <= 193) return true
}
if(measurement === 'in') {
if(Number(heightVal) >= 59 && Number(heightVal) <= 76)return true
}
}
break
case 'hcl':
if(value.match(/#[0-9a-fA-F]{6}/)) return true
break
case 'ecl':
if(value.length !== 3) return false
if(value.match(/amb|blu|brn|gry|grn|hzl|oth/)) return true
break
case 'pid':
if(value.length !== 9) return false
if(Number(value)) return true
break
case 'cid':
return true
break
default:
break
}
return false
}
var counter = 0
passports.forEach(p => {
var fields = p.trim().split(' ')
if(fields.length === 8 || (fields.length === 7 && p.indexOf('cid') === -1)){
if(fields.every(f => isValid(f))) counter++
}
})
console.log(counter)