Skip to content

Instantly share code, notes, and snippets.

@brianphillips
Last active December 26, 2015 23:39
Show Gist options
  • Save brianphillips/7232200 to your computer and use it in GitHub Desktop.
Save brianphillips/7232200 to your computer and use it in GitHub Desktop.
use strict;
use warnings;
use Math::Combinatorics qw(combine);
use List::Util qw(sum);
my $target = shift || 0;
my %pairs = (
#a => 1, b => 2, c => 3,
#d => 2, e => 1, f => 0,
#g => 4, h => 8, i => 7,
#j => 10
( a => 1, b => 7, c => 3, d => 5 )
);
my %sums;
my $k = 1;
while($k <= keys %pairs){
my @sets = combine($k, keys %pairs);
foreach my $s(@sets){
my $key = join(' + ', sort @$s);
if(sum(@pairs{@$s}) == $target){
$sums{$key} = $target;
}
}
$k++;
}
foreach my $key(sort {$a cmp $b || length($a) <=> length($b) } keys %sums) {
print "$key == $sums{$key}\n" if $sums{$key} == $target || 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment