24 points is small game. You must use +
-
*
/
to get the result 24 from 4 numbers. I wrote a Perl script to solve this problem. But I feel my code is too long and it looks like C.
I hope someone can give me some advice. Thank you very much!
Other language are possible, too, for example Python, Scala, F#, C++.
my @test_arr = (10, 4, 7, 6);
my @oprator_arr = ('+', '-', '*', '/');
rec_cala(\@test_arr);
sub rec_cala {
my ($arr_ref) = @_;
my @input_arr = ();
push @input_arr, @$arr_ref;
if (scalar(@input_arr) <= 1) {
$result = eval $input_arr[0];
if ($result > 23.9 && $result < 24.1) {
print $input_arr[0];
print " = 24\n";
}
} else {
my @perm_arr = perm(\@input_arr);
foreach (@perm_arr) {
my @next_arr = @$_;
my $op1 = pop @next_arr;
my $op2 = pop @next_arr;
foreach (@oprator_arr) {
@op_expr_arr = @next_arr;
push @op_expr_arr, "($op1 $_ $op2)";
rec_cala(\@op_expr_arr);
}
}
}
}
sub perm {
my ($arr_ref) = @_;
my @arr = @$arr_ref;
my @result = [];
while (scalar(@arr)) {
my $curr_element = pop @arr;
my @next_step = ();
foreach $curr_array (@result) {
$curr_len = scalar(@$curr_array);
for ($i = 0; $i <= $curr_len; $i++) {
push @next_step, [
(@$curr_array[0 .. $i], $curr_element, @$curr_array[$i + 1 .. $curr_len])
];
}
}
@result = @next_step;
}
return @result;
}