Whilst it is true that no element is repeated, for the purposes of the OP, this solution will produce multiple results for the same three elements being summed in a different order. Some form of filtering, perhaps involving a numerical sort of element numbers, a pack to a string and a grep with a %seen hash, would be required to remove duplicates.
Update: Here's some code to show what I mean. All the faff with pack q{N*}, @{ $_ } is because we may be dealing with larger arrays where subscripts go into multiple digits. This code:-
use 5.026; use warnings; use Algorithm::Permute; my @arr = ( 1, 2, 3, 4, 5 ); my $perm = Algorithm::Permute->new( [ 0 .. $#arr ], 3 ); my @allPerms; while ( my @res = $perm->next() ) { push @allPerms, [ sort { $a <=> $b } @res ]; } my @uniqPerms = do { my %seen; map { [ unpack q{N*}, $_ ] } grep { ! $seen{ $_ } ++ } sort map { pack q{N*}, @{ $_ } } @allPerms }; say join q{+}, @{ $_ } for @uniqPerms;
Produces:-
0+1+2 0+1+3 0+1+4 0+2+3 0+2+4 0+3+4 1+2+3 1+2+4 1+3+4 2+3+4
Cheers,
JohnGG
In reply to Re^4: Sum of N elements in an M element array
by johngg
in thread Sum of N elements in an M element array
by abhay180
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |