Below is a sub I've written to figure out all the possible arrangements of the elements of an array. Is there a cleaner and/or more efficient way to do this? I'm assuming that it would be possible to do this by swapping elements, thereby not copying the array each time, but I can't determine the order you'd need to swap them in.
sub combinations {
my @array = @_;
if ($#array == 0) {return [ $array[0] ]; }
my @results;
my $element;
foreach $element (0..$#array) {
my @leftovers = @array;
my $chosen_one = splice(@leftovers, $element, 1);
foreach (&combinations(@leftovers)) {
push(@results, [ $chosen_one, @{$_} ]);
}
}
return @results;
}
use Data::Dumper;
print Dumper(&combinations(qw(a b c d)));