Advent of Code, Day 2: Password Philosophy
Go to Day 2 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
"Each line gives the password policy and then the password. The password policy indicates the lowest and
highest number
of times a given letter must appear for the password to be valid. For example, 1-3 a means that the password
must contain a
at least 1 time and at most 3 times."
ref
var nums = window.document.getElementsByTagName("pre")[0]
nums = nums.innerText.split('\n')
var counter = 0;
nums.forEach(pwd => {
var a = pwd.match(/([0-9]*)-([0-9]*)\s(.):\s([a-zA-Z]*)/)
if(a && a.length > 4) {
var min = Number(a[1])
var max = Number(a[2])
var letter = a[3]
var password = a[4]
if(password.indexOf(letter) > -1) {
var regx = new RegExp(letter, 'ig')
var letterCount = password.match(regx)
if(letterCount.length >= min && letterCount.length <= max) {
console.log(password,'is valid')
counter++;
}
}
} else {
console.error(pwd, 'not a valid password and policy')
}
});
console.log(counter, 'out of', nums.length, 'passwords are legit')
Part II
"Each policy actually describes two positions in the password, where 1 means the first character,
2 means the second character, and so on. (Be careful; Toboggan Corporate Policies have no concept of
"index zero"!) Exactly one of these positions must contain the given letter. Other occurrences of the
letter are irrelevant for the purposes of policy enforcement."
ref
var nums = window.document.getElementsByTagName("pre")[0]
nums = nums.innerText.split('\n')
var counter = 0;
nums.forEach(pwd => {
var a = pwd.match(/([0-9]*)-([0-9]*)\s(.):\s([a-zA-Z]*)/)
if(a && a.length > 4) {
var min = Number(a[1]) - 1
var max = Number(a[2]) - 1
var letter = a[3]
var password = a[4]
var hasMin = password.substring(min, min+1) === letter
var hasMax = password.substring(max, max+1) === letter
if(hasMin !== hasMax) {
console.log(password,'is valid')
counter++;
}
} else {
console.error(pwd, 'not a valid password and policy')
}
});
console.log(counter, 'out of', nums.length, 'passwords are legit')