in reply to Re^2: Recursion problem
in thread Recursion problem
Iterating over all combinations is as simple as counting. Think of all values in the array to be calculated as being 0s or 1s. If it is a 1, the value is included and if it is 0, it isn't. For instance:
5 -6 8 10 12 3 10 0 0 0 0 0 0 1 = 10 0 0 0 0 0 1 0 = 3 0 0 0 0 0 1 1 = 3, 10 0 0 0 0 1 0 0 = 12 0 0 0 0 1 0 1 = 12, 10 ... 1 1 1 1 1 1 1 = 5, -6, 8, 10, 12, 3, 10
#!/usr/bin/perl use strict; use warnings; use List::Util 'sum'; my @amount = (5, -6, 8, 10, 12, 3, 10); my $count = @amount; for (1 .. 2 ** $count - 1) { my @bit = split //, sprintf("%.${count}b", $_); my $total = sum( map {$bit[$_] ? $amount[$_] : 0 } 0 .. $#bit); print "$total\n"; }
Cheers - L~R
|
|---|