$Test_String = <STDIN> ; if($Test_String =~ /$Regex_Pattern/){ print "true"; } else { print "false"; }
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,
1110110001 => 00111, 10101 7 21 3 * 7 = 21, accept!
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:
use bigint; sub check { my ($bin, $three) = ('0b') x 2; my $s = $_; while ($s) { $three .= chop $s; $bin .= chop $s; } return oct $three == 3 * oct $bin } $Regex_Pattern = qr/(?{ check() })/;
The problem here is that (?{...}) always matches. Fortunately, you can use the code pattern as the condition in
(?(condition)yes-pattern|no-pattern)
As the yes-pattern, I used ^ which always matches, and (*FAIL) for the no-pattern:
$Regex_Pattern = qr/^(?(?{ check() }) ^ | (*FAIL) )/x;
The qr adds some characters, so to be sure I don't overflow, I renamed the subroutine to c and golfed the solution to
'^(?(?{c()})^|(*F))'
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!
($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Regular Expreso 2
by oiskuu (Hermit) on Apr 27, 2016 at 17:29 UTC | |
|
Re: Regular Expreso 2
by morgon (Priest) on Apr 27, 2016 at 02:22 UTC | |
by Your Mother (Archbishop) on Apr 27, 2016 at 03:05 UTC |