Snippet Name: Permutation Generator
Description: This Permutation Generator will produce all of the possible combinations of the items given to it.
Comment: (none)
Language: PHP
Highlight Mode: PHP
Last Modified: March 01st, 2009
|
<?PHP
FUNCTION permutations($letters,$num){
$last = STR_REPEAT($letters{0},$num);
$result = ARRAY();
WHILE($last != STR_REPEAT(lastchar($letters),$num)){
$result[] = $last;
$last = char_add($letters,$last,$num-1);
}
$result[] = $last;
RETURN $result;
}
FUNCTION char_add($digits,$string,$char){
IF($string{$char} <> lastchar($digits)){
$string{$char} = $digits{STRPOS($digits,$string{$char})+1};
RETURN $string;
}ELSE{
$string = changeall($string,$digits{0},$char);
RETURN char_add($digits,$string,$char-1);
}
}
FUNCTION lastchar($string){
RETURN $string{STRLEN($string)-1};
}
FUNCTION changeall($string,$char,$start = 0,$end = 0){
IF($end == 0) $end = STRLEN($string)-1;
FOR($i=$start;$i<=$end;$i++){
$string{$i} = $char;
}
RETURN $string;
}
?>
To use this Generator, call it like this :
<?
$Array=permutations("ABC",3);
FOR($i=0 ; $i < COUNT($Array) ; $i++) {
ECHO "$i." . $Array[$i] . "<BR>";
}
?>
The output would look like this :
0.AAA
1.AAB
2.AAC
3.ABA
4.ABB
5.ABC
6.ACA
7.ACB
8.ACC
9.BAA
10.BAB
11.BAC
12.BBA
13.BBB
14.BBC
15.BCA
16.BCB
17.BCC
18.CAA
19.CAB
20.CAC
21.CBA
22.CBB
23.CBC
24.CCA
25.CCB
26.CCC
|