Created
March 20, 2015 13:45
-
-
Save h3xx/0ee2412222bcc2e69ec3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl -w | |
use strict; | |
=head2 permute($arrayref) | |
Gives all permutations of a given set of elements. Stolen straight out of B. Heap's HeapPermute algorithm. | |
$ fxpr 'permute [0..1]' | |
[ 0 1 ] | |
[ 1 0 ] | |
$ fxpr 'permute [0..2]' | |
[ 0 1 2 ] | |
[ 1 0 2 ] | |
[ 2 0 1 ] | |
[ 0 2 1 ] | |
[ 1 2 0 ] | |
[ 2 1 0 ] | |
=cut | |
sub permute { | |
my ($alphabet, $n, $current_set, $sets) = @_; | |
$sets = [] unless defined $sets; | |
$current_set = [ @{$alphabet} ] unless defined $current_set; | |
$n = @{$alphabet} unless defined $n; | |
if ($n == 1) { | |
push @{$sets}, [ @{$current_set} ]; | |
} else { | |
foreach my $i (0 .. ($n-1)) { | |
&permute($alphabet, $n-1, $current_set, $sets); | |
if ($n % 2) { | |
# n is odd | |
($current_set->[0], $current_set->[$n-1]) = | |
($current_set->[$n-1], $current_set->[0]); | |
} else { | |
# n is even | |
($current_set->[$i], $current_set->[$n-1]) = | |
($current_set->[$n-1], $current_set->[$i]); | |
} | |
} | |
} | |
@{$sets} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment