Greetings,
The question was solve 9 ? -4 ? 8 ? 6 ? 10 = 7 by inserting (/ * + -) operators.
1- Allow relocation of numbers.
2- No operator should be used more than once.
3- Operations left to right.

My solution:
use strict; use Algorithm::Combinatorics qw(variations); use feature ':5.10'; my @operators = qw(+ - * /); my @numbers = qw(9 -4 8 6 10); my $total = 7; #required result my $iter = variations(\@operators, 4); #get combinations for operators + without rep. my $iter2 = variations(\@numbers, 5); #get combinations for numbers w +ithout rep. while (my $p = $iter->next){ while (my $p2 = $iter2->next){ #escaping precedence my $eval = eval ("$p2->[0] $p->[0] $p2->[1]"); $eval = eval ("$eval $p->[1] $p2->[2]"); $eval = eval ("$eval $p->[2] $p2->[3]"); $eval = eval ("$eval $p->[3] $p2->[4]"); if ($eval == $total){ say "$p2->[0] ($p->[0]) $p2->[1] ($p->[1]) $p2->[2] ($p->[2]) $p2- +>[3] ($p->[3]) $p2->[4] = $total"; } } $iter2 = variations(\@numbers, 5); #Resets the iterator }

I hope this code sports good Perl practices.
Special thanks to MidLifeXis.

Replies are listed 'Best First'.
Re: Automating solving missing Arithmetic operators
by wind (Priest) on Apr 07, 2011 at 06:33 UTC

    Cool little script. I've used Algorithm::Combinatorics as well recently and found it to be a very helpful module.

    Here's your script streamlined just a little bit. As the documentation points out, variations(\@data, scalar @data) is equivalent to permutations(\@data).

    use Algorithm::Combinatorics qw(permutations); use strict; my @numbers = qw(9 -4 8 6 10); my @operators = qw(+ - * /); my $total = 7; #required result my $num_iter = permutations(\@numbers); while (my $nums = $num_iter->next){ my $op_iter = permutations(\@operators); while (my $ops = $op_iter->next) { my $str = $nums->[0]; $str = "($str $ops->[$_] " . $nums->[$_+1] . ")" for (0..3); if ($total == eval $str) { print "$str = $total\n"; } } }
      Great enhancements! now it's more elegant with calculation's part. Thanks
Re: Automating solving missing Arithmetic operators
by ikegami (Patriarch) on Apr 07, 2011 at 05:34 UTC
    You need to find the permutations (ordered), which is what you do despite the comment that you are finding combinations (unordered).
      Yes sir you are correct, I didn't mean combinations in the mathematical sense (this modules combinations function). I should be more careful with the words.