Sum to 100: Difference between revisions

Add Perl
(→‎Batch processing: Rigt-to-left turned out to be about as messy.)
(Add Perl)
Line 4,061:
</pre>
 
=={{header|Perl}}==
{{works with|Perl|5.10}}
<lang perl>#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
 
my $string = '123456789';
my $length = length $string;
my @possible_ops = ("" , '+', '-');
 
{
my @ops;
sub Next {
return @ops = (0) x ($length) unless @ops;
 
my $i = 0;
while ($i < $length) {
if ($ops[$i]++ > $#possible_ops - 1) {
$ops[$i++] = 0;
next
}
# + before the first number
next if 0 == $i && '+' eq $possible_ops[ $ops[0] ];
 
return @ops
}
return
}
}
 
sub evaluate {
my ($expression) = @_;
my $sum;
$sum += $_ for $expression =~ /([-+]?[0-9]+)/g;
return $sum
}
 
my %count = ( my $max_count = 0 => 0 );
 
say 'Show all solutions that sum to 100';
 
while (my @ops = Next()) {
my $expression = "";
for my $i (0 .. $length - 1) {
$expression .= $possible_ops[ $ops[$i] ];
$expression .= substr $string, $i, 1;
}
my $sum = evaluate($expression);
++$count{$sum};
$max_count = $sum if $count{$sum} > $count{$max_count};
say $expression if 100 == $sum;
}
 
say 'Show the sum that has the maximum number of solutions';
say "sum: $max_count; solutions: $count{$max_count}";
 
my $n = 1;
++$n until ! exists $count{$n};
say "Show the lowest positive sum that can't be expressed";
say $n;
 
say 'Show the ten highest numbers that can be expressed';
say for (sort { $b <=> $a } keys %count)[0 .. 9];</lang>
{{Out}}
<pre>Show all solutions that sum to 100
123-45-67+89
12-3-4+5-6+7+89
12+3+4+5-6-7+89
123+4-5+67-89
-1+2-3+4+5+6+78+9
1+2+3-4+5+6+78+9
12+3-4+5+67+8+9
1+23-4+56+7+8+9
1+2+34-5+67-8+9
1+23-4+5+6+78-9
123+45-67+8-9
123-4-5-6-7+8-9
Show the sum that has the maximum number of solutions
sum: 9; solutions: 46
Show the lowest positive sum that can't be expressed
211
Show the ten highest numbers that can be expressed
123456789
23456790
23456788
12345687
12345669
3456801
3456792
3456790
3456788
3456786</pre>
=={{header|Perl 6}}==
{{works with|Rakudo|2017.03}}
Anonymous user