Esempio n. 1
0
function filterEquationBrackets($q)
{
    $serializedEquation = serializeEquationToArray($q);
    $equation = deserializeArrayToEquation($serializedEquation);
    $filteredSerializedEquation = filterBracketBySerializedEquation($serializedEquation);
    return deserializeArrayToEquation($filteredSerializedEquation);
}
Esempio n. 2
0
function filterBracketBySerializedEquation($serializedEquation, $prevOperator = null, $nextOperator = null)
{
    if (!is_array($serializedEquation)) {
        return $serializedEquation;
    }
    foreach ($serializedEquation as $key => &$subEquation) {
        // skip if not array
        if (!is_array($subEquation)) {
            continue;
        }
        // get previous and next operator
        $prevOperator = isset($serializedEquation[$key - 1]) ? $serializedEquation[$key - 1] : $prevOperator;
        $nextOperator = isset($serializedEquation[$key + 1]) ? $serializedEquation[$key + 1] : $nextOperator;
        // set is remove bracket flag
        $isRemoveBracket = true;
        foreach ($subEquation as $subKey => $c) {
            // if not operator, skip
            if (!in_array($c, array('+', '-', '*', '/'))) {
                continue;
            }
            // case by case, for +, -, *, /
            switch ($c) {
                case '+':
                case '-':
                    if (in_array($prevOperator, array('-', '*', '/')) || in_array($nextOperator, array('*', '/'))) {
                        $isRemoveBracket = false;
                    }
                    break;
                case '*':
                case '/':
                    if ($prevOperator == '/') {
                        $isRemoveBracket = false;
                    }
                    break;
                default:
                    break;
            }
        }
        // remove unnecessary brackets
        if ($isRemoveBracket) {
            array_shift($subEquation);
            array_pop($subEquation);
        }
        // recursive filter unnecessary brackets
        $subEquation = filterBracketBySerializedEquation($subEquation, $prevOperator, $nextOperator);
    }
    unset($subEquation);
    return $serializedEquation;
}