在PHP中输出真值表

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了在PHP中输出真值表脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我跑过这个 truth table generator site,并试图用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

并有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

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

这个递归函数怎么样?它返回一个维数组,其中每个’row’都有$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));

编辑:Codepad,具有将数组转换为表格的附加功能.

脚本宝典总结

以上是脚本宝典为你收集整理的在PHP中输出真值表全部内容,希望文章能够帮你解决在PHP中输出真值表所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。