XP is just a number | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
This is not a solution, but a tale of a solution that didn't work out. I thought: hey, why not solve it with regexes? First, convert the number $n to a string of length $n, 1 x $n. Then write a regex that matches only strings of lengths that are powers of two. then do (1 x $n) =~ /^(?:($that_regex)(?{ say length $1}))* and be happy. You can recursively define powers of two as
That should be straight forward to mold into a regex, no? After all, our regexes are recursive:
Unfortunately Perl 5 does not agree: Infinite recursion in regex The problem is that as soon as all the 1s are exhausted, the regex engine endlessly recurses (the (?1) branch) while not consuming any characters. So, if only the end is the problem, maybe we can just stop recursing when we're at the end of the string? Look-aheads to the rescue:
And indeed, it matches. But it only ever matches chunks of length 1, because the left alternative is tried first. So the |1 would need to go at the end, but then it's still infinite recursion, because the recursion occurs before consuming any characters. I know this isn't what regexes are meant for, but I'd still like it to work. Unfortunately I've run out of ideas for now. Does anybody know how to fix it? In reply to Re: mini-golf: convert integer into list of powers of two
by moritz
|
|