http://www.perlmonks.org?node_id=11123894


in reply to Find combination of numbers whose sum equals X

#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11123870 use warnings; use List::Util qw( uniq ); print "$_\n" for find( 100, '1 99 2 40 50 60 90 3 5 95 100' ); print "\n"; print "$_\n" for find( 100, '5 5 5 5 10 15 80 99' ); sub find { my ($target, $from, $have) = @_; $have //= ''; $target == 0 and return $have =~ s/.//r; $target > 0 && $from =~ s/\d+// or return (); uniq find( $target - $&, $from, "$have+$&"), find( $target, $from, +$have ); }

Outputs:

1+99 2+40+50+3+5 2+90+3+5 2+3+95 40+60 5+95 100 5+5+5+5+80 5+5+10+80 5+15+80