Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Re: mini-golf: convert integer into list of powers of two

by moritz (Cardinal)
on May 24, 2012 at 08:13 UTC ( #972199=note: print w/replies, xml ) Need Help??

in reply to mini-golf: convert integer into list of powers of two

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

n_0 = 1 n_i = n_(i-1) + n_(i-1)

That should be straight forward to mold into a regex, no? After all, our regexes are recursive:

say (1 x 5) =~ /^(1|((?1))\2)*$/

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:

(1 x 5) =~ /^(?:(1|((?=1)(?1))\2)(?{ say length $1 }))*$/

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?

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://972199]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (2)
As of 2021-05-12 05:51 GMT
Find Nodes?
    Voting Booth?
    Perl 7 will be out ...

    Results (124 votes). Check out past polls.