I am trying to make a script that generates every possible combination from an array of elements. I have found a script that does it, but it is too intensive and takes extremely long to generate anything that has more than 7 elements inside the array.
I am trying to achieve, where from an array of:
array("Quick", "Brown", "Fox");
I would get a result of:
Quick Brown Fox
Quick Fox Brown
Brown Quick Fox
Brown Fox Quick
Fox Quick Brown
Fox Brown Quick
As you can see, that a single word never repeats itself, and there are only unique generations, as well as it always uses all elements of the array, so it never returns less elements than the length of array.
Here is the code that I am currently using:
function f_($n) {
if($n<2) { return 1; }
for($x = 2;$n-1>1;$x*=$n--);
return $x;
}
function array_restore($r) {
$clean = array();
if(is_array($r)) {
foreach($r as $k) {
$clean[] = $k;
}
}
return $clean;
}
function connect($arr){
$back = "";
foreach($arr as $a){
if($back != ""){
$back .= " ";
}
$back .= $a;
}
return $back;
}
function cmb($v) {
$str = count($v);
$tot = f_($str);
$combo = array();
for($i=0;$i<$tot*8;$i++) {
shuffle($v);
$sf = connect($v);
if(!in_array($sf, $combo)){
$combo[] = $sf;
}
}
$x = array_unique($combo);
return array_restore($x);
}
var_dump(cmb(array("Quick", "Brown", "Fox")));
EDIT: I found a bit better algorithm, seems like its impossible to make anything even quicker, so I will have to find a different way to approach my problem.
function pc_permute($items, $perms = array( )) {
$back = array();
if (empty($items)) {
$back[] = join(' ', $perms);
} else {
for ($i = count($items) - 1; $i >= 0; --$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
$back = array_merge($back, pc_permute($newitems, $newperms));
}
}
return $back;
}