Skip to content

Instantly share code, notes, and snippets.

@davidbella
Created November 4, 2012 23:02
Show Gist options
  • Save davidbella/4014245 to your computer and use it in GitHub Desktop.
Save davidbella/4014245 to your computer and use it in GitHub Desktop.
CueUp/greplin Level 3 - Subset Sums
use strict;
use warnings;
use Math::Combinatorics;
my @numbers = (3, 4, 9, 14, 15, 19, 28, 37, 47, 50, 54, 56, 59, 61, 70, 73, 78, 81, 92, 95, 97, 99);
my $total = 0;
for (my $sum = 0; $sum < scalar @numbers; $sum++) {
next if ($sum < 3);
my @leftArray;
for (my $i = 0; $i < $sum; $i++) {
push @leftArray, $numbers[$i];
}
for (my $subsetSize = 2; $subsetSize < $sum; $subsetSize++) {
my @subsets = combine($subsetSize, @leftArray);
foreach my $subset (@subsets) {
my $sumVal = eval join '+', @$subset;
if ($sumVal == $numbers[$sum]) {
print join(' + ', @$subset), " = ", $numbers[$sum], "\n";
$total++;
}
}
}
}
print $total, "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment