Perl: Ineffective Script to Permute Words

I just wrote a script that rearranges every letter in a word. It works very ineffectively, though it does complete the task.

while (<STDIN>) {
   chomp;
   @w = split //;
   $m = 1;
   for (my $i = 1; $i <= @w; $i++) {
      $m *= $i;
   }
   $i = 0;
   for (my $n = 0; $n < $m; $i++) {
      $v = join('',@w);
      if (!exists($ws{$v})) {
         $n++;
         $ws{$v} = 1;
         print "$v\\n";
      }
      $rn = rand(@w);
      $rm = rand(@w);
      ($w[$rn],$w[$rm]) = ($w[$rm],$w[$rn]);
   }
   print "(only " . $i . " attempts)\\n";
   undef %ws;
}

As long as the word is less than eight characters, it will go fairly fast. Unfortunately you can’t use it for words containing several instances of the same letter, but since there is absolutely no practical usage for this script anyway, that should not be a problem.

Maybe Related?

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

FireStats iconAnvänder FireStats