gpt4 book ai didi

php - 在 PHP 中输​​出真值表

转载 作者:可可西里 更新时间:2023-11-01 13:13:44 26 4
gpt4 key购买 nike

我遇到了这个 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

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

最佳答案

这个递归函数怎么样?它返回一个二维数组,其中每个“行”都有 $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 中输​​出真值表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9291987/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com