Page 1 of 1

Permutation - generate list

Posted: Wed Nov 02, 2011 11:51 am
by JKM
Hi there!

Let's say I got this string: $str = 'ABCDEFGIJKLMNOPQRSTUVWXUZ123456789", and I want to echo a list of possible combinations, given a $length.
$length = 2;
=> A1, A2, A3, A4 ... 1A, 2A ... Z1, Z2, Z3 ...
$length = 5;
=> AAAA1, AAAA2 ... 1111A, 1111 ... ZZZZ1 ZZZZ2 ...

Thanks! :)

Re: Permutation - generate list

Posted: Wed Nov 02, 2011 12:30 pm
by manohoo
I did it for length 2 and 3, maybe you can figure out a function that will take the length as an argument. But be careful, you might burn your CPU! Just kidding.

Code: Select all

$str = 'ABCDEFGIJKLMNOPQRSTUVWXUZ123456789';
$str = str_split($str);

// length = 2
foreach ($str as $v1) {
   foreach ($str as $v2) {
      echo "$v1$v2<br />";
   }
}

// length = 3
foreach ($str as $v1) {
   foreach ($str as $v2) {
      foreach ($str as $v3) {
         echo "$v1$v2$v3<br />";
      }
   }
}

Re: Permutation - generate list

Posted: Wed Nov 02, 2011 6:29 pm
by JKM
Thanks!

If I do a length=5 - does that mean that it's 5^36 number of combinations?
14 551 915 200 000 000 000 000 000 combinations seems a bit high... :p