Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>One algorithm is here,</p> <pre><code>function getCombinations($base,$n){ $baselen = count($base); if($baselen == 0){ return; } if($n == 1){ $return = array(); foreach($base as $b){ $return[] = array($b); } return $return; }else{ //get one level lower combinations $oneLevelLower = getCombinations($base,$n-1); //for every one level lower combinations add one element to them that the last element of a combination is preceeded by the element which follows it in base array if there is none, does not add $newCombs = array(); foreach($oneLevelLower as $oll){ $lastEl = $oll[$n-2]; $found = false; foreach($base as $key =&gt; $b){ if($b == $lastEl){ $found = true; continue; //last element found } if($found == true){ //add to combinations with last element if($key &lt; $baselen){ $tmp = $oll; $newCombination = array_slice($tmp,0); $newCombination[]=$b; $newCombs[] = array_slice($newCombination,0); } } } } } return $newCombs; } </code></pre> <p>I know it is not efficent in any way, but using in small sets should not be a problem</p> <p>first base parameter is an array containing elements to be considered when generating combinations.</p> <p>for simple usage and output:</p> <pre><code>var_dump(getCombinations(array("a","b","c","d"),2)); </code></pre> <p>and output is</p> <pre><code>array 0 =&gt; array 0 =&gt; string 'a' (length=1) 1 =&gt; string 'b' (length=1) 1 =&gt; array 0 =&gt; string 'a' (length=1) 1 =&gt; string 'c' (length=1) 2 =&gt; array 0 =&gt; string 'a' (length=1) 1 =&gt; string 'd' (length=1) 3 =&gt; array 0 =&gt; string 'b' (length=1) 1 =&gt; string 'c' (length=1) 4 =&gt; array 0 =&gt; string 'b' (length=1) 1 =&gt; string 'd' (length=1) 5 =&gt; array 0 =&gt; string 'c' (length=1) 1 =&gt; string 'd' (length=1) </code></pre> <p>To list all subsets of an array, using this combinations algorithm just execute</p> <pre><code>$base =array("a","b","c","d"); for($i = 1; $i&lt;=4 ;$i++){ $comb = getCombinations($base,$i); foreach($comb as $c){ echo implode(",",$c)."&lt;br /&gt;"; } } </code></pre> <p>And output is</p> <pre><code>a b c d a,b a,c a,d b,c b,d c,d a,b,c a,b,d a,c,d b,c,d a,b,c,d </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload