DEV Community

Cover image for Advent of code - Day 4
Quentin Ménoret
Quentin Ménoret

Posted on • Updated on

Advent of code - Day 4

Are you participating in the Advent of code this year?

If you don't know what the advent of code is, it's a website where you'll find a daily challenge (every day it gets harder). It's a really fun event, you should participate!

I try to solve the exercises using either JavaScript or TypeScript and will share my solutions daily (with one day delay so no one can cheat!). I only share the solution for the second part.

For day #4 I actually created 2 different solution. The first one was using a lot of different Regex:

input
  .split(/\r?\n\r?\n/)
  .filter((passport) => /byr:(19[2-9][0-9]|200[0-2])(\s|$)/.test(passport))
  .filter((passport) => /iyr:(201[0-9]|2020)(\s|$)/.test(passport))
  .filter((passport) => /eyr:(202[0-9]|2030)(\s|$)/.test(passport))
  .filter((passport) =>
    /hgt:((1[5-8][0-9]|19[0-3])cm)|(59|6[0-9]|7[0-6])in/.test(passport)
  )
  .filter((passport) => /hcl:\#[0-9a-f]{6}(\s|$)/.test(passport))
  .filter((passport) =>
    /ecl:(amb|blu|brn|gry|grn|hzl|oth)(\s|$)/.test(passport)
  )
  .filter((passport) => /pid:\d{9}(\s|$)/.test(passport));
Enter fullscreen mode Exit fullscreen mode

But As you can see, every filter contains a Regex... So I took the time to have some fun and group them into one. Don't try this at home!

const rg = /(?=(.|\n)*byr:(19[2-9][0-9]|200[0-2])(\s|$))(?=(.|\n)*iyr:(201[0-9]|2020)(\s|$))(?=(.|\n)*eyr:(202[0-9]|2030)(\s|$))(?=(.|\n)*hcl:\#([0-9a-f]{6})(\s|$))(?=(.|\n)*ecl:(amb|blu|brn|gry|grn|hzl|oth)(\s|$))(?=(.|\n)*pid:(\d{9})(\s|$))(?=(.|\n)*(hgt:((1[5-8][0-9]|19[0-3])cm)|(59|6[0-9]|7[0-6])in))/;

const result = input.split(/\r?\n\r?\n/).filter((passport) => rg.test(passport));
Enter fullscreen mode Exit fullscreen mode

But since there are some people even crazier than me, someone from my team adapted this code so it doesn't require any preprocessing (no need to split the string anymore!).

Here is the solution, with only a Regex:

const monster = /(?=(?:.|[^\n]\n)*byr:(?:19[2-9][0-9]|200[012])(?:\s|$))(?=(?:.|[^\n]\n)*iyr:20(?:1[0-9]|20)(?:\s|$))(?=(?:.|[^\n]\n)*eyr:20(?:2[0-9]|30)(?:\s|$))(?=(?:.|[^\n]\n)*hgt:(?:(?:59|6[0-9]|7[0-6])in|1(?:(?:[5-8][0-9]|9[0-3])cm))(?:\s|$))(?=(?:.|[^\n]\n)*hcl:#[0-9a-f]{6}(?:\s|$))(?=(?:.|[^\n]\n)*ecl:(?:amb|blu|brn|gry|grn|hzl|oth)(?:\s|$))(?=(?:.|[^\n]\n)*pid:[0-9]{9}(?:\s|$))([\w\W]+?)(?:\n\n|$)/g;

const result = input.match(monster).length;
Enter fullscreen mode Exit fullscreen mode

Feel free to share yours in the comments!


Photo by Markus Spiske on Unsplash

Top comments (0)