I was all impressed that I got over a 300% increase from your original code which should get better with larger combinations sets until I saw
's code. Here it is anyway:
#!/usr/bin/perl
use strict;
use warnings;
use Algorithm::Loops 'NestedLoops';
my ($val, $sum, $count, $key);
my (%seen, %uniq);
my (@matches, @key);
my ($amount, $depth) = (28, 7);
my $RS = [10, 5, 13, 3, 15, 1, 4];
NestedLoops( [ ( $RS ) x $depth ], { OnlyWhen => \&ok }, sub{} );
print_results();
sub ok {
$count++;
%uniq = ();
$sum = 0;
for $val ( @_ ) {
$uniq{$val}++;
return 0 if $uniq{$val} > 1;
$sum += $val;
return 0 if $sum > $amount;
}
$key = join " " , sort {$b <=> $a} @_;
return 0 if exists $seen{$key};
$seen{$key} = undef;
push @matches , $key if $sum == $amount;
}
sub print_results {
my %convert;
@convert{ @$RS } = 'A' .. 'H';
print "Searched $count combinations...\n";
for my $match ( @matches ) {
for my $value ( split " " , $match ) {
print "$convert{$value} ";
}
print "\n";
}
}