hi,

I have this code, mentioned below:

my @word = qw(a b c );
my $length = @word;
my $char1, $char2, $char3;

if ($length == 3){
for ($char1 = 0; $char1<$len;$char1++){
 for ($char2 = 0; $char2<$len;$char2++){
  for ($char3 = 0; $char3<$len;$char3++){
    print "$word[$char1]$word[$char2]$word[$char3]\n";
}}}
}elsif($length == 2){
 for ($char2 = 0; $char2<$len;$char2++){
  for ($char3 = 0; $char3<$len;$char3++){
    print "$word[$char1]$word[$char2]\n";
}elsif($length == n){
....
....
and so on...
}


Then as suggested (see far below), a recursive function will do what I want.. 
After some googling I found this:


permutate(0,2);

sub permutate($$){

  my ($cur,$max) = @_;
  
  if ($cur>=$max){
     print "$result\n";
     return;
  }

  for(@word){
    substr($result,$cur,1)=$_;
    perm($cur+1,$max);
  }
}


Can anyone tell me how the code above works? My original program must deal with 
arbitrary length and generate all the possible combinations (even repeating) of 
a particular set. What could take me gazillions of for loops for that, somebody 
just came up with less than ten lines. 
I can just copy and paste the code I found above but I want to learn how it 
works. How could someone write this code so easily but when I tried even 
writing just a pseudocode for it, my head almost exploded. 

I want to be a good programmer, but at this rate, I don't think I can be one if 
I will just keep copying and pasting someone else's code or downloading modules 
from CPAN.

Can anyone teach me how my own code (the one with gazillion for loops), can be 
converted into a pseudocode then eventually into a working sub procedure?




--- On Sun, 10/25/09, Gabor Szabo <szab...@gmail.com> wrote:

> > Hi,
> >
> >  I'm trying to write a word list generator which can
> >  generate all possible combinations of n characters,
> within n
> >  set of characters.
> >
> >
> >  So far, this is what I have come up. The only input
> is the
> >  lenght of the password the user wants.
> >

....

> What about keeping the characters in an array @char
> so you will have
> $char[0], $char[1] etc. a
> 
> nd the loops could be replaced by a recursive function
> call. Something
> like this:
> 
> do_something_for_char($k)
> 
> sub do_something_for_char {
>   my ($k) = @_;
>   return if $k >= $n;
>    do_something_for_char($n+1);
> }
> 
> 
> Gabor
> 





--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to