Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Find combination of numbers whose sum equals X

by tybalt89 (Prior)
on Nov 20, 2020 at 12:44 UTC ( #11123894=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11123894]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2021-01-25 01:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?