Re: Perl 'Medium' Quiz-of-the-Whatever for 2009-08-11 : Plusified Equations

Peter Scott <[email protected]> Mon, 12 Oct 2009 12:54:23 -0700
Newsgroups gmane.comp.lang.perl.qotw.discuss
Message-ID <[email protected]>
Here's my solution, which also uses binary number counting to decide 
where to put the + signs.  I have been unable to remove the duplicated 
code without making it much less clear and no shorter.

use strict;
use warnings;

my ($left, $right) = @ARGV;

my ($count_left, $count_right) = map { length() - 1 } ($left, $right);

for my $left_num ( 0 .. 2**$count_left - 1)
{
   my $left = $left;
   my $i = $count_left;
   $left =~ s/(.)(?=.)/$1 . ($left_num & 1 << --$i ? '+' : '')/ge;

   for my $right_num ( 0 .. 2**$count_right - 1 )
   {
     my $right = $right;
     my $i = $count_right;
     $right =~ s/(.)(?=.)/$1 . ($right_num & 1 << --$i ? '+' : '')/ge;
     print "$left == $right\n" if eval $left == eval $right;
   }
}
-- 
Peter Scott
Pacific Systems Design Technologies
http://www.perldebugged.com/
http://www.perlmedic.com/
http://www.informit.com/store/product.aspx?isbn=0137001274