下面的關聯數組表示不同的變量(由鍵值標識)及其各自的邏輯運算符,以便與它們的鄰居進行比較 - 它們的鄰居是它們下面的變量。在PHP中求解布爾變量的算法
Array(
[x] => or
[y] => and
[z] => or
[v] => null
)
我試圖找出一種算法,將採取上述的數據結構,並把它翻譯爲下列表達式:
$result = lookup('x') || lookup('y') && lookup('z') || lookup('v');
哪裏lookup($id)
是查找的布爾值的函數給定的字符串$id
並返回它。因此,如果x = true,則Y =真,Z =假,和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以哪種語言出現? – Cups 2014-12-07 00:58:33