Sunday, June 9, 2013

Truth Table / Power Set


Output:
0 0 0 
0 0 1 
0 1 0 
0 1 1 
1 0 0 
1 0 1 
1 1 0 
1 1 1 

printTruthTable("", 0, 3);

$originalArr = array('a', 'b', 'c');
$outputArr = array();
powerSet("", 0, 3);
var_dump($outputArr);

function printTruthTable($str, $start, $strLength) {
  if ($start === $strLength) {
    if (/*Truth Table*/) {
      var_dump($str);
    }
    if (/*Power Set*/) {
      global $originalArr;
      global $outputArr;
      
      $tempArr = array();
      for($i=0; $i<$strLength; $i++){
        if ($str[$i] === 1) {
          array_push($tempArr, $originalArr[$i]);
        }
      }
      array_push($outputArr, $tempArr);
    }
    
    return;
  }
  $str[$start] = 0;
  printTruthTable($str, $start+1, $strLength);
  
  $str[$start] = 1;
  printTruthTable($str, $start+1, $strLength);
}

OR

function printPowerSet($set, $set_size)
{
    /*set_size of power set of a set with set_size
      n is (2**n -1)*/
    $pow_set_size = pow(2, $set_size);
 
    for($counter = 0; $counter < $pow_set_size; $counter++)
    {
      for($j = 0; $j < $set_size; $j++)
       {
          if($counter & (1 << $j))
            echo $set[$j]; // echo 
       }
       echo PHP_EOL;
    }
}
 
$set = 'abc';
printPowerSet($set, 3);