Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Divide an array into 2 subsets to verify their sum is equal or not.

by hdb (Monsignor)
on May 02, 2013 at 09:47 UTC ( [id://1031716]=note: print w/replies, xml ) Need Help??


in reply to Divide an array into 2 subsets to verify their sum is equal or not.

Using recursion:

use strict; use warnings; use List::Util qw/sum/; # finds one solution sub findsum { my ($target, @array) = @_; while( @array ) { my $cand = shift @array; return () if $cand > $target; return ( $cand ) if $cand==$target; my @sol = findsum( $target-$cand, @array ); return ($cand, @sol) if @sol; } return (); } my @array = qw(1 3 5 7); my $total = sum(@array); die "Odd total $total cannot be split!\n" if $total % 2; my @sol = findsum( $total/2, sort @array ); if( @sol ) { print "Solution: ",join( ",", @sol), "\n"; } else { print "No solution."; }
  • Comment on Re: Divide an array into 2 subsets to verify their sum is equal or not.
  • Download Code

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (2)
As of 2024-04-26 00:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found