Return to JUNTO

JUNTO Practice: Advent of Code 2019: Day 4 - Secure Container

Discussed on January 09, 2020.

https://adventofcode.com/2019/day/4

Solutions

Click to see:

Oscar Martinez

hasDouble = (i) => {
  iString = i.toString();
  for (j = 0; j < iString.length; j++) {
  if (j != iString.length - 1) {
  if (iString[j] === iString[j + 1]){
        return true;
        }
    }
  }
  return false;
}

neverDecreases = (i) => {
  iString = i.toString();
  maxInt = 0;
  for (j = 0; j < iString.length; j++) {
  currentInt = parseInt(iString[j],10);
    if (currentInt < maxInt) {
      return false
    }
    maxInt = currentInt
  }
  return true;
}

inputRange = range(156218, 652527);
candidates = inputRange.filter((input) => {
return hasDouble(input) && neverDecreases(input)
});

console.log(candidates)
console.log(`${candidates.length} is the final answer.`)

John Lekberg

Part 1

function checkPassword(p) {
  const digits = [...String(p)];
  let same = false;
  for (let i = 0; i < digits.length - 1; i++) {
    const d = digits[i];
    const dd = digits[i+1];
    if (dd < d) {
      return false;
    }
    if (dd === d) {
      same = true;
    }
  }
  return same;
}

let howMany = 0;
for (let p = 134792; p <= 675810; p++) {
  if (checkPassword(p)) {
    howMany++;
  }
}
console.log(howMany);

Part 2

function checkPassword2(p) {
  const digits = [...String(p)].map(x => +x);
  let same2 = false;
  for (let i = 0; i < digits.length - 1; i++) {
    if (digits[i+1] < digits[i]) {
      return false;
    }
    if (digits[i] === digits[i+1]) {
      if (i > 0 && digits[i-1] === digits[i]) {
        continue;
      }
      if (i < 4 && digits[i+1] === digits[i+2]) {
        continue;
      }
      same2 = true;
    }
  }
  return same2;
}

let howMany2 = 0;
for (let p = 134792; p <= 675810; p++) {
  if (checkPassword2(p)) {
    howMany2++;
  }
}
console.log(howMany2);