DEV Community

Mahmoud Ashraf
Mahmoud Ashraf

Posted on • Originally published at mahmoudashraf.dev

2 1

Advent of Code 2020: Day 02

Originally Published on my blog

Day 02

part 01 ⭐

We have a list of passwords with validation rules,
So we should validate each password and submit the
total number of valid passwords.

1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc
Enter fullscreen mode Exit fullscreen mode

First, let's create an parser to extract information from each line.

const getPasswordsList = () =>
  readFileSync(path.resolve(__dirname, 'input.txt'), 'utf8')
    .split('\n')
    .filter(Boolean)
    .map((i) => i.split(/[-,:,\s]+/));
Enter fullscreen mode Exit fullscreen mode

We read the input.txt file and convert it into an array by split each line using
.split(\n) then we will use regex to extract min, max, target, and password
on each line by using multi separator: -, :, and \s for space.

If you interred to learn more about split with regex I highly recommend to watch
Regular Expressions: split() - Programming with Text video.

Now we are ready to write the validator function:

function getValidPasswordsP1(passwords) {
  return passwords.reduce((ans, [min, max, letter, password]) => {
    const count = password.match(new RegExp(letter, 'g'))?.length;
    return count >= +min && count <= +max ? ++ans : ans;
  }, 0);
}
Enter fullscreen mode Exit fullscreen mode

part 02 ⭐

Actually the part two is a lot easier than the part one it assume the first two numbers
are the positions for the target letter to only occurs in one of them.

function getValidPasswordsP2(passwords) {
  return passwords.reduce((ans, [pos1, pos2, letter, password]) => {
    return (password.charAt(+pos1 - 1) === letter) ^
      (password.charAt(+pos2 - 1) === letter)
      ? ++ans
      : ans;
  }, 0);
}
Enter fullscreen mode Exit fullscreen mode

Use the bitwise XOR to make sure it only occurs in only exact one position.

You can check the MDN reference.

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay