我跑过这个
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,具有将数组转换为表格的附加功能.