DEV Community

Discussion on: Advent of Code 2019 Solution Megathread - Day 4: Secure Container

Collapse
 
maxart2501 profile image
Massimo Artizzu

My solution in JavaScript, with some regex magic.

const start = 123257;
const end = 647015;

function isMonotone(pwd) {
  return pwd.split('').every((digit, index) => index === 0 || digit >= pwd[index - 1]);
}
function hasGroupOfTwo(pwd) { // For part 1
  return /(\d)\1/.test(pwd);
}
function hasGroupOfOnlyTwo(pwd) { // For part 2
  return (pwd.match(/(\d)\1+/g) || []).map(sequence => sequence.length).includes(2);
}
function isCandidate(pwd) {
  return hasGroupOfTwo(pwd) && isMonotone(pwd);
}

let validCount = 0;
for (let pwd = start; pwd <= end; pwd++) {
  validCount += isCandidate(String(pwd));
}

console.log(validCount);

For the second part, replace hasGroupOfTwo with hasGroupOfOnlyTwo in isCandidate.

Check out my solutions at github.com/MaxArt2501/advent-of-co...