Re: A little arithmetic puzzle

Jed Davis <[email protected]>
Newsgroups gmane.comp.lang.perl.fun
Organization Chaotic
Message-ID <[email protected]>
Jasvir Nagra <[email protected]> writes:

> #!/usr/bin/perl -lw
>
> use Quantum::Superpositions;
> use strict;
>
> my $tree = my $num = any(1,5,6,7);
> my $op = any qw!+ - / *!;
>
> $tree =  any eigenstates "($num $op $tree)",
>              eigenstates "($tree $op $num)"
>   for 1..3;
>
> print grep { 21 == eval and not /(\d).*\1/ } eigenstates $tree;
> __END__


#!/usr/bin/perl

sub permu {
    return ([]) unless @_;
    map { my $i=$_; map { [$_[$i],@$_] } permu(@_[0..$_-1,$_+1..$#_]) } 0..$#_;
}

sub combi {
    my $n; ($n,@_)=@_; return ([]) unless $n;
    map { my $i=$_; map { [@$i,$_] } @_ } combi($n-1,@_);
}
    
for $tree ("(%s %s %s) %s (%s %s %s)",
	   "((%s %s %s) %s %s) %s %s",
	   "(%s %s (%s %s %s)) %s %s",
	   "%s %s ((%s %s %s) %s %s)",
	   "%s %s (%s %s (%s %s %s))") {
    for $nums (permu(1,5,6,7)) {
	for $ops (combi(3,'+','-','*','/')) {
	    my $expr = sprintf(sprintf($tree,map{$_,"%s"}@$nums),@$ops);
	    print "$expr\n" if 21 == eval $expr;
	}
    }
}
__END__

In retrospect, I could also have put %%s in the format strings instead
of using that map.

-- 
Jed Davis               |"But life wasn't yes-no, on-off.  Life was shades of
<[email protected]>        | gray, and rainbows not in the order of the spectrum."
<[email protected]>|   -- L. E. Modesitt, Jr., _Adiamante_
PGP key (fingerable) F33659F9 A098:903E:9B9A:DEF4:168F:AA09:BF07:807E:F336:59F9
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.