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?


In reply to Re: mini-golf: convert integer into list of powers of two by moritz
in thread mini-golf: convert integer into list of powers of two by xyzzy

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.