Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outputting a truth table in PHP

Tags:

php

truthtable

I ran across this truth table generator site, and tried to mimic it in PHP (i realize the source code is available, but i know 0 perl).

Now my question is not about evaluating the expression, but how to output the table so that every combination of T and F for the variables is shown

For example, with 3 variables, the table would look like such:

a | b | c 
-----------
T | T | T  
T | T | F 
T | F | T 
T | F | F 
F | T | T 
F | T | F 
F | F | T 
F | F | F 

and with 4 variables..

a | b | c | d
-------------
T | T | T | T
T | T | T | F
T | T | F | T
T | T | F | F
T | F | T | T
T | F | T | F
T | F | F | T
T | F | F | F
F | T | T | T
F | T | T | F
F | T | F | T
F | T | F | F
F | F | T | T
F | F | T | F
F | F | F | T
F | F | F | F

What is the logic/pattern to create it?

like image 752
sqram Avatar asked Feb 15 '12 10:02

sqram


2 Answers

How about this recursive function? It returns a 2-dimensional array where each 'row' has $count elements. You can use this to generate your table.

function getTruthValues($count) {
    if (1 === $count) {
        // true and false for the first variable
        return array(array('T'), array('F'));
    }   

    // get 2 copies of the output for 1 less variable
    $trues = $falses = getTruthValues(--$count);
    for ($i = 0, $total = count($trues); $i < $total; $i++) {
        // the true copy gets a T added to each row
        array_unshift($trues[$i], 'T');
        // and the false copy gets an F
        array_unshift($falses[$i], 'F');
    }   

    // combine the T and F copies to give this variable's output
    return array_merge($trues, $falses);
}

function toTable(array $rows) {
    $return = "<table>\n";
    $headers = range('A', chr(64 + count($rows[0])));
    $return .= '<tr><th>' . implode('</th><th>', $headers) . "</th></tr>\n";

    foreach ($rows as $row) {
        $return .= '<tr><td>' . implode('</td><td>', $row) . "</td></tr>\n";
    }

    return $return . '</table>';
}

echo toTable(getTruthValues(3));

EDIT: Codepad, with an added function to convert the array to a table.

like image 152
cmbuckley Avatar answered Oct 11 '22 12:10

cmbuckley


$nbBooleans = 5; // change to whatever you want

// show header

for($i = 0; $i < $nbBooleans ; $i++) {
  if ($i > 0) {
    echo " | ";
  }
  echo chr($i + 65); // 1 => A, 2 => B etc.
}

// separator line (dynamic size)

echo "\n".str_repeat("-", ($nbBooleans - 1) * 3 + $nbBooleans)."\n";

// show combinations

$nbInterations = pow(2, $nbBooleans);

for($i = 0; $i < $nbInterations; $i++) {
  for ($iBit = 0; $iBit < $nbBooleans; {
    if ($iBit > 0) {
      echo " | ";
    }
    echo (($i & pow(2, $iBit)) != 0 ? 'Y' : 'N');
  }
  echo "\n";
}
like image 37
Frosty Z Avatar answered Oct 11 '22 12:10

Frosty Z