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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.