Re: A little arithmetic puzzle

Rob Williams <[email protected]>
Newsgroups gmane.comp.lang.perl.fun
Message-ID <[email protected]>
Brute force, but still fairly fast.

#!/usr/bin/perl
use strict;
my @symbols = qw(+ - / *);
my %done;
while (1) {
        my $equ;
        $equ .= "$_".$symbols[int(rand(4))] for (sort { (-1,1)[rand 2] } 
qw(1 5 6 7));
        chop($equ);
        while (!$done{$equ}++){
                &ev($equ, @$_) for 
([0,4],[0,0,5,8],[0,0,6,5,13,14],[2,6],[2,8],[2,14]);   #could add more 
I guess.
        }
}
sub ev {
        my ($exp, @arr) = @_;
        my @exp = split '', $exp;
        my $cnt = 0;
        for (@arr) {
                my $br = (++$cnt <= (scalar(@arr) / 2)) ? '(' : ')';
                splice(@exp,$_,0,$br);
        }
        $exp = join '', @exp;
        (print "$exp\n" and exit) if eval(join '', $exp) == 21;
}
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.