Enumeration

Just had a need to enlist all the combination there are for an array of objects and here is how to list them up all.

Here is the idea: the combination, as is this enumeration is called in Math world, could be expressed in 0s and 1s in that, if you enlist the whole combination, it will be the same as the array of numbers expressed in binary. Each item is either in (1) or out (0) then the total of the combination will be 2 to the power of the number of items.

In PHP, the binary is shifted one bit by one bit and checked throughly whether the item index is in or out. The resultant array will be put in another array, so what the function returns is an array of arrays.

function enumerate($max)
{
  $power=1;
  for($i=0;$i<$max;$i++)
    $power*=2;

  $comb=array();
  for($i=0;$i<$power;$i++)
    {
      $t=$i;
      $j=0;
      $arr=array();
      while(0<$t)
	{
	  if($t&0x1==0x1)
	    array_push($arr,$j);
	  $t=$t>>1;
	  $j++;
	}
      if(0<count($arr))
	array_push($comb,$arr);
    }
  return $comb;
}

inserted by FC2 system