Anonymous user
Subset sum problem: Difference between revisions
→{{header|Perl}}: Sort hash for consistency, use new ntheory with loop exit construct
(Added Kotlin) |
(→{{header|Perl}}: Sort hash for consistency, use new ntheory with loop exit construct) |
||
Line 1,052:
{{libheader|ntheory}}
<lang perl>use ntheory qw/:all/;
my %pairs = (
Line 1,063 ⟶ 1,062:
mincemeat => -880, moresby => 756, mycenae => 183, plugging => -266,
smokescreen => 423, speakeasy => -745, vein => 813 );
# sort so we get the same order each time
my @
my @weights = @pairs{@names}; # hash slice gives all values in same order
▲ foreach my $n (1 .. @names) {
forcomb {
# Remove the "lastfor, " to get all combinations
lastfor, print "Length $n: @names[@_]\n"
} @names, $n;
}</lang>
Printing just the first one found for each number of elements:
Line 1,091 ⟶ 1,076:
<pre>
Length 2: archbishop gestapo
Length 3:
Length 4:
Length 5:
Length 6:
Length 7:
Length 8:
Length 9: alliance archbishop balm bonnet brute covariate eradicate mincemeat plugging
... to length 27 ...
</pre>
We can also use different modules for this brute force method. Assuming the same pairs/names/weights variables
<lang perl>use List::Util qw/sum/;
use Algorithm::Combinatorics qw/combinations/;
|