在PHP中输出真值表

sqr*_*ram 6 php truthtable

我跑过这个真值表生成器站点,并试图用PHP模仿它(我意识到源代码是可用的,但我知道0 perl).

现在我的问题不是评估表达式,而是如何输出表格,以便显示变量的T和F的每个组合

例如,对于3个变量,表格看起来像这样:

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 
Run Code Online (Sandbox Code Playgroud)

并有4个变量..

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
Run Code Online (Sandbox Code Playgroud)

创建它的逻辑/模式是什么?

cmb*_*ley 4

这个递归函数怎么样?它返回一个二维数组,其中每个“行”都有$count元素。您可以使用它来生成您的表。

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));
Run Code Online (Sandbox Code Playgroud)

编辑Codepad,添加了将数组转换为表的功能。