php - All combinations of 2D array with mutual exclusivity -


i have array looks this:

$i[0] = ['a', 'b', 'c']; $i[1] = ['d', 'e']; $i[2] = ['a', 'b', 'c']; $i[3] = ['d', 'e']; $i[4] = ['f', 'g', 'h']; 

i want possible permutations or combinations of array, without using same value twice 2 or more sub-arrays. instance, result a d b e f possible, not a d d f.

i have tried basic permutation algorithms, can't wrap head around how modify want.

here's i've got currently:

function array_permutation(array $a){     $count = array_map('count', $a);     $finalsize = 1;      foreach ($count $val) {         $finalsize *= $val;     }      $output = [];      ($i = 0; $i < $finalsize; $i++) {         $output[$i] = [];         ($c = 0; $c < count($a); $c++) {             $index = ($i + $finalsize) % $count[$c];             array_push($output[$i], $a[$c][$index]);         }     }     return $output; } 

a simple approach plain loop:

function decartproductexclusive($one, $two) {    $result = [];    for($i=0; $i<count($one); $i++)    {       for($j=0; $j<count($two); $j++)       {          if(!count(array_intersect((array)$one[$i], (array)$two[$j])))          {             $result[]=array_merge((array)$one[$i], (array)$two[$j]);          }       }    }    return $result; }  function createassociation() {    $args   = func_get_args();    if(!count($args))    {       return [];    }    $result = array_shift($args);    while($array=array_shift($args))    {       $result=decartproductexclusive($result, $array);    }    return $result; }  $i[0] = ['a', 'b', 'c']; $i[1] = ['d', 'e']; $i[2] = ['a', 'b', 'c']; $i[3] = ['d', 'e']; $i[4] = ['f', 'g', 'h'];  $result = call_user_func_array('createassociation', $i); 

(check fiddle) issue evaluating cartesian product, condition, tuple can not contain repeated elements. condition, however, may fulfilled without evaluating intersection in each iteration (that overkill). instead can filter resulting array, using array_unique(), in this fiddle.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -