Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: finding values in an array that add up to a specific number

by GrandFather (Saint)
on Jul 27, 2005 at 00:22 UTC ( [id://478420]=note: print w/replies, xml ) Need Help??


in reply to finding values in an array that add up to a specific number

Math::Combinatorics helps with generating the combinations.

use strict; use warnings; use Math::Combinatorics; my @array = (6, 18, 12, 2, 49); my @sums = (30, 18); for my $target (@sums) { for (1..@array) { my @combs = Math::Combinatorics::combine ($_, @array); for my $comb (@combs) { my $sum = 0; map {$sum += $_} @$comb; next if $sum != $target; print "$target = " . (join " + ", @$comb) . "\n"; } } }
30 = 12 + 18 18 = 18 18 = 12 + 6

Perl is Huffman encoded by design.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2024-04-23 13:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found