Your skill will accomplish what the force of many cannot |
|
PerlMonks |
Regular Expresso 2by choroba (Cardinal) |
on Apr 26, 2016 at 20:24 UTC ( [id://1161591]=perlmeditation: print w/replies, xml ) | Need Help?? |
As you might have noticed, I like programming puzzles and brain teasers. But I hadn't participated in a real public contest... until today. I registered to Regular Expresso 2 on HackerRank. The participants had 24 hours to solve 8 tasks, Perl was among the supported languages. The contest was regular expression-centered, your code had to always end the same:
The top 10 contestants (most points + shortest time) won a T-shirt. Once I realised there were more then 10 people with the full score, I knew I wasn't getting one, but I still wanted to get the full score. But I had no idea how to solve one of the tasks: the input was a long string of zeroes and ones. Your regex had to recognise whether the string encoded two binary numbers in the following way: when you reversed the string and extracted the odd digits, you got a number three times greater than the one built from the remaining digits. For example,
I wrote a short script to generate some examples, but I wasn't able to find the pattern. Moreover, the regex couldn't have more than 40 characters! Then I remembered Perl has a way to run code in a regex: the (?{...}) pattern. I read the relevant perlre section several times and tried something like the following:
The problem here is that (?{...}) always matches. Fortunately, you can use the code pattern as the condition in
As the yes-pattern, I used ^ which always matches, and (*FAIL) for the no-pattern:
The qr adds some characters, so to be sure I don't overflow, I renamed the subroutine to c and golfed the solution to
I got the full score! Would you call such a solution cheating? On one hand, I see that's not what the organisers wanted me to do, on the other hand, that's what Perl regular expressions give you. In fact, with the "start or fail" pattern, I can solve almost any problem with a regular expression!
Back to
Meditations
|
|