diff options
author | jluehrs2 <jluehrs2@uiuc.edu> | 2008-01-31 03:49:51 -0500 |
---|---|---|
committer | jluehrs2 <jluehrs2@uiuc.edu> | 2008-01-31 03:49:51 -0500 |
commit | 5960d197c36cff4fefcb0bb8ed11cba9d9865407 (patch) | |
tree | 13f07eb37e67ee34f6fa0083f7a72abeb78d21cd | |
parent | b1ae1086a4fcfa69c7fa70e5964923a7c9e1003c (diff) | |
download | games-word-5960d197c36cff4fefcb0bb8ed11cba9d9865407.tar.gz games-word-5960d197c36cff4fefcb0bb8ed11cba9d9865407.zip |
implement random_permutation and is_permutation
-rw-r--r-- | lib/Games/Word.pm | 31 |
1 files changed, 29 insertions, 2 deletions
diff --git a/lib/Games/Word.pm b/lib/Games/Word.pm index b0f37f8..0b57357 100644 --- a/lib/Games/Word.pm +++ b/lib/Games/Word.pm @@ -2,8 +2,35 @@ package Games::Word; use strict; use warnings; - - +use Math::Combinatorics qw/factorial/; +use Test::Deep::NoTest; + +sub random_permutation { + my $word = shift; + return '' if $word eq ''; + + use integer; + my $len = length $word; + my $perm_index = shift; + $perm_index = defined($perm_index) ? $perm_index : + int(rand(factorial($len))); + die "invalid permutation index" if $perm_index >= factorial($len) || + $perm_index < 0; + my $current_index = $perm_index / factorial($len - 1); + my $rest = $perm_index % factorial($len - 1); + + my $first_letter = substr($word, $current_index, 1); + substr($word, $current_index, 1) = ''; + + return $first_letter . random_permutation($word, $rest); +} + +sub is_permutation { + my @word_letters = split //, shift; + my @perm_letters = split //, shift; + + return eq_deeply(\@word_letters, bag(@perm_letters)); +} =head1 NAME |