Created
January 1, 2011 09:22
-
-
Save pjlsergeant/761648 to your computer and use it in GitHub Desktop.
This file contains 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
sub permutation { | |
my ( $desired_permutation, $column_count, $permutation_set ) = @_; | |
my $permutation_set_count = @$permutation_set; | |
# The total number of permutations | |
my $total_permutations = $permutation_set_count ** $column_count; | |
# Return if we're being asked for a permutation outside the total number | |
# possible | |
return if $desired_permutation >= $total_permutations; | |
# Calculate the desired_permutation in base x where x = $permutations_set_count | |
my $num = $desired_permutation; | |
my $base = $permutation_set_count; | |
my $s = []; | |
while (1) { | |
my $r = $num % $base; | |
unshift( @$s, $r ); | |
$num = int($num / $base); | |
last if $num == 0; | |
} | |
while ( @$s < $column_count ) { | |
unshift( @$s, 0 ); | |
} | |
# @$s is now a list corresponding to the permutation, where each number is | |
# an index of the permutation set | |
# Now we build the permutation by substituting those for the set | |
return join '|', map { $permutation_set->[$_] } @$s; | |
} | |
my $i=0; | |
while (1) { | |
my $p = permutation( $i++, 3, [qw( 0 3 6 9 C F )] ); | |
if ( defined $p ) { | |
print "$p\n"; | |
} else { | |
last; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment