DEV Community

Mahmoud Ashraf
Mahmoud Ashraf

Posted on • Originally published at mahmoudashraf.dev

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.

Top comments (0)