算24代码

算24代码
do24(5,5,5,1);
# (5-1/5)*5=24
sub do24{
my $ok=0;
my @n=@_;
my @f=qw(+ - * /);
print "$n[0]\t$n[1]\t$n[2]\t$n[3]:\n";
for my $n1(0..3){
for my $n2(0..3){
next if $n2==$n1;
for my $n3(0..3){
next if ($n3==$n2 or $n3==$n1);
for my $n4(0..3){
next if ($n4==$n3 or $n4==$n2 or $n4==$n1);
for my $f1(@f){
for my $f2(@f){
for my $f3(@f){
my $num1=$n[$n1];
my $num2=$n[$n2];
my $num3=$n[$n3];
my $num4=$n[$n4];
my $temp1="$num1$f1$num2$f2$num3$f3$num4";#abcd
my $temp2="($num1$f1$num2)$f2$num3$f3$num4" if ($f1 ne '*' and $f1 ne '/' and $f2 ne '+' and $f2 ne '-');#(ab)cd
my $temp3="($num1$f1$num2$f2$num3)$f3$num4" if ($f3 ne '+' and $f3 ne '-');#(abc)d
my $temp4="$num1$f1($num2$f2$num3)$f3$num4"if ($f1 ne '*' and $f1 ne '/');#a(bc)d
my $temp5="$num1$f1($num2$f2$num3$f3$num4)" if ($f1 ne '+' and $f1 ne '-');#a(bcd)
my $temp6="$num1$f1$num2$f2($num3$f3$num4)" if ($f3 ne '*' and $f3 ne '/' and $f2 ne '+' and $f2 ne '-');#ab(cd)
my $temp7="($num1$f1$num2)$f2($num3$f3$num4)" if ($f2 ne '+' and $f2 ne '-');#(ab)(cd)
my $temp = qq{print "\$temp1\\n" and \$ok++ if $temp1==24;};
$temp .= qq{print "\$temp2\\n" and \$ok++ if $temp2==24;} if $temp2;
$temp .= qq{print "\$temp3\\n" and \$ok++ if $temp3==24;} if $temp3;
$temp .= qq{print "\$temp4\\n" and \$ok++ if $temp4==24;} if $temp4;
$temp .= qq{print "\$temp5\\n" and \$ok++ if $temp5==24;} if $temp5;
$temp .= qq{print "\$temp6\\n" and \$ok++ if $temp6==24;} if $temp6;
$temp .= qq{print "\$temp7\\n" and \$ok++ if $temp7==24;} if $temp7;
eval $temp;
}
}
}
}
}
}
}
print "Sorry for NO answer\n" and print "no answer!\n" if $ok<1;
print "\n";
}
####################
__END__
#算所有数的24值
$|=1;
for my $x1 (1..10){
for my $x2($x1..10){
for my $x3($x2..10){
for my $x4($x3..10){
do24($x1,$x2,$x3,$x4);
}
}
}
}

This Just Is MR.WATER!