DEV Community

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

Collapse
 
mellen profile image
Matt Ellen • Edited

Regex to the rescue!

function passwordcount()
{
    let inputtext = document.querySelector('.puzzle-input').innerHTML;
    let pwrange = inputtext.split('-').map(v => parseInt(v, 10));
    let pwcount = 0;
    //let consecutivesame = /(11|22|33|44|55|66|77|88|99|00)/; /*for part 1*/
    let consecutivesame = /(([^1]|^)11([^1]|$)|([^2]|^)22([^2]|$)|([^3]|^)33([^3]|$)|([^4]|^)44([^4]|$)|([^5]|^)55([^5]|$)|([^6]|^)66([^6]|$)|([^7]|^)77([^7]|$)|([^8]|^)88([^8]|$)|([^9]|^)99([^9]|$)|([^0]|^)00([^0]|$))/;
    for(let i = pwrange[0]; i < pwrange[1]; i++)
    {
        let istr = i.toString();
        let iparts = istr.split('');
        let sortstr = iparts.sort().join('');
        if(sortstr == istr && consecutivesame.test(istr))
        {
            pwcount++;
        }
    }
    return pwcount;
}

Just to make it clear: ([^1]|^)11([^1]|$) says:

  • ([^1] find anything other than 1 | or ^) the beginning of the string. The parentheses create a capture group that allows the use of | to mean "or".
  • 11 find "11"
  • ([^1] find anything other than 1 | or $) the end of the string.

Essentially this searches for "11" surrounded by anything that isn't a 1. Then I repeated it for the other digits.

Collapse
 
katafrakt profile image
Paweł Świątkowski

Wow, nice solution.

Collapse
 
coolshaurya profile image
Shaurya

Interesting, I used the same regex for my part 1 too

Collapse
 
mellen profile image
Matt Ellen

Nice solution. I've not used rust, but I hear it's really fast!

Collapse
 
neilgall profile image
Neil Gall

Nice, although I wouldn't inflict that on my team-mates!

Collapse
 
mellen profile image
Matt Ellen

It is a bit of a monster.

I've being trying to think of a way to refine it, but then again I'm not likely to be asked to find numbers like that outside of AoC :D

Collapse
 
jbristow profile image
Jon Bristow

Even I, someone who loves regexes so much that I made a regex that converted words to Pig Latin, find this hard to read!

It makes sense! I just worry that if I look away from it for too long it will have changed...

It’s still more readable than the regex that “matches a b c where a+b=c” (a,b,c being any rational number)

Thread Thread
 
mellen profile image
Matt Ellen

Wow. ._.