Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regex for words 1

Status
Not open for further replies.

rdyoll

Technical User
Aug 11, 2003
39
US
...suppose I want to find all possible combinations of any word.

$string = param('string');

If the string was, say, frost, what would I need to write to get all combinations of the letters in one shot.

frost
tsorf
rostf
ostfr
stfro
tfros
sorft
orfst
and so forth...

I know I need to put the 'string' into some array of some sort, but I'm stuck. The most I could come up with is to reverse it.

$stringrev = reverse$string;

@string = (); # ???

for $_(@string) {
## clueless
}

Thanx
 
I'm still a perl newbie, but I got something that kinda works. It just gives all possible permutations of the letters in a word so if there are duplicate letters there will be some duplicate permutations.

Code:
#!/usr/bin/perl

use strict;

my $word = shift;
my @letters = split(//, $word);
&permutate(\@letters);

my @used_letters;

sub permutate{
  my $array_ref = shift;
  my @letters = @$array_ref;
  my $length = @letters;

  for(my $i = 0; $i < $length; $i++){
    my $letter = $letters[$i];
    push(@used_letters,$letter);
    if($length == 1){
      print &quot;@used_letters\n&quot;;
      pop(@used_lettesr);
      return;}
    my @temp;
    for(my $j = 0; $j < $length; $j++){
      if($i != $j){
      push(@temp, $letters[$j]);}
    }
    &permutate(\@temp);
    pop(@used_letters);
  }
}
 
Oops, got a typo in there... pop(@used_lettesr) should be pop(@used_letters);
 
...PERFECT, worx exactly as I wanted...I knew repeat letters would give duplicates, but that's not an issue...thank you very much...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top