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;
}
- A little arithmetic puzzle Rob Williams
- A little arithmetic p... Jasvir Nagra
- Re: A little arit... Jonathan E. Paton
- simple rpn de... Bennett Todd
- Re: simpl... Simon Cozens
- Re: simpl... Chris Dolan
- Re: ... PerlDiscuss - Perl Newsgroups and mailing lists
- Re: simpl... Philippe 'BooK' Bruhat
- Re: A little ... Yitzchak Scott-Thoennes
- Re: A lit... Rick Klement
- Re: ... Jasvir Nagra