Permutation - generate list

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
JKM
Forum Contributor
Posts: 221
Joined: Tue Jun 17, 2008 8:12 pm

Permutation - generate list

Post 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! :)
User avatar
manohoo
Forum Contributor
Posts: 201
Joined: Wed Dec 23, 2009 12:28 pm

Re: Permutation - generate list

Post 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 />";
      }
   }
}
JKM
Forum Contributor
Posts: 221
Joined: Tue Jun 17, 2008 8:12 pm

Re: Permutation - generate list

Post 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
Post Reply