PHP Power Set

Here is a snippet that shows how to get the power set of an array.

/**
* Takes the power set of a one dimensional array and returns a 2-D array.
* array(a,b,c) ->
* array(array(a),array(b),array(c),array(a,b),array(b,c),array(a,b,c))
*/
function powerSet($in,$minimumNumber = 1) {
   $count = count($in);
   $members = pow(2,$count);
   $return = array();
   for ($i = 0; $i < $members; $i++) {
      $b = sprintf("%0".$count."b",$i);
      $out = array();
      for ($j = 0; $j < $count; $j++) {
         if ($b{$j} == '1') $out[] = $in[$j];
      }
      if (count($out) >= $minimumNumber) {
         $return[] = $out;
      }
   }
   return $return;
}

Tags:

One Response to “PHP Power Set”

  1. melissa Says:

    coinslot!

Leave a Reply