in reply to check possible combination of sum using given array
Here's one idea for an algorithm. Getting the output into the @want_output array is left up to you.
#!/usr/bin/perl # https://perlmonks.org/?node_id=11102502 use strict; use warnings; my @input = qw/ 2 5 7 /; my $target = 15; print "\ntarget $target from @input\n"; find( 0, [], $target, @input ); print "That's all, folks\n"; $target = 3; print "\ntarget $target from @input\n"; find( 0, [], $target, @input ); print "That's all, folks\n"; $target = 35; print "\ntarget $target from @input\n"; find( 0, [], $target, @input ); print "That's all, folks\n"; sub find { my ($sum, $sofar, $want, @numbers ) = @_; if( $sum == $want ) { print "@$sofar\n"; } elsif( $sum < $want and @numbers and $numbers[0] > 0 ) { find( $sum + $numbers[0], [ @$sofar, $numbers[0] ], $want, @number +s ); find( $sum, $sofar, $want, @numbers[1..$#numbers] ); } }
Outputs:
target 15 from 2 5 7 2 2 2 2 2 5 2 2 2 2 7 5 5 5 That's all, folks target 3 from 2 5 7 That's all, folks target 35 from 2 5 7 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 5 2 2 2 2 2 2 2 2 2 2 2 2 2 2 7 2 2 2 2 2 2 2 2 2 2 5 5 5 2 2 2 2 2 2 2 2 2 5 5 7 2 2 2 2 2 2 2 2 5 7 7 2 2 2 2 2 2 2 7 7 7 2 2 2 2 2 5 5 5 5 5 2 2 2 2 5 5 5 5 7 2 2 2 5 5 5 7 7 2 2 5 5 7 7 7 2 5 7 7 7 7 5 5 5 5 5 5 5 7 7 7 7 7 That's all, folks
|
|---|