【发布时间】:2014-12-07 00:43:59
【问题描述】:
下面的关联数组表示不同的变量(由键值标识)和它们各自的逻辑运算符以与它们的邻居进行比较 - 它们的邻居是它们下面的变量。
Array(
[x] => or
[y] => and
[z] => or
[v] => null
)
我正在尝试找出一种算法,该算法将采用上述数据结构并将其转换为以下表达式:
$result = lookup('x') || lookup('y') && lookup('z') || lookup('v');
其中lookup( $id ) 是一个函数,它查找给定字符串$id 的布尔值并返回它。因此,如果 x = true、y = true、z = false 和 v = false,则上面的计算结果为:
$results = true || true && false || false; // should evaluate to true
这是我目前所拥有的:
$bool_vars = array( 'x' => 'or', 'y' => 'and', 'z' => 'or', 'v' => null);
$keys = array_keys( $bool_vars ); // Grab the variable identifiers
$result = lookup( $keys[0] ); // Get the bool value of the first variable
// If there is more than one var, we need to evaluate the boolean expression
if( count($keys) > 1 ){
foreach( $keys as $k => $key ){
// No need to evaluate the last element since it has no neighbor
if( $k + 1 == count( $keys ) ){ break; }
$operator = $bool_vars[ $key ]; // Get the logical operator to use
// Filter by operator
switch( $operator ){
case 'or':
// Get the bool value of the next var
$result = $result || isset( lookup( $keys[$k + 1] ) );
break;
case 'and':
$result = $result && isset( $lookup( $keys[$k + 1] ) );
break;
default:
continue;
}
}
}
return $result;
只是想用另一双眼睛来确保上述内容有意义 - 我已经多次运行此算法,但似乎有几次它没有返回正确的布尔值。
【问题讨论】:
-
v 出现在 z 之后是哪种语言?
标签: php algorithm boolean-logic boolean-expression