/** * Tokenize a soap type * * @param string $type Type * * @return array Tokens */ public static function tokenize($type) { $stack = new Stack(); $stack->push(SOAP_STATE_DEFAULT); $stack->push(SOAP_STATE_TYPE); $tokens = array(); $token = ''; $len = strlen($type); // We don't actually care whether we're inside of a type or not // That's why there aren't separate states for inside and outside of braces for ($pos = 0; $pos < $len; ++$pos) { $char = $type[$pos]; $nextChar = isset($type[$pos + 1]) ? $type[$pos + 1] : null; switch ($stack->top()) { case SOAP_STATE_DEFAULT: if (ctype_alnum($nextChar)) { $stack->push(SOAP_STATE_TYPE); } elseif (in_array($char, self::$whitespace)) { $tokens[] = array('code' => SOAP_WHITESPACE, 'token' => $char); } elseif ($char === '{') { $tokens[] = array('code' => SOAP_OPEN_BRACE, 'token' => $char); } elseif ($char === '}') { $tokens[] = array('code' => SOAP_CLOSE_BRACE, 'token' => $char); } elseif ($char === ';') { $tokens[] = array('code' => SOAP_SEMICOLON, 'token' => $char); } break; case SOAP_STATE_TYPE: if (ctype_alnum($char)) { $token .= $char; if ($nextChar === ' ') { if (in_array($token, self::$nativeTypes)) { $tokens[] = array('code' => SOAP_NATIVE_TYPE, 'token' => $token); } else { $tokens[] = array('code' => SOAP_USER_TYPE, 'token' => $token); } $token = ''; $stack->pop(); $stack->push(SOAP_STATE_PROPERTY); } } break; case SOAP_STATE_PROPERTY: if (ctype_alnum($char)) { $token .= $char; if ($nextChar === ';' || $nextChar === ' ' || $nextChar === null) { $tokens[] = array('code' => SOAP_PROPERTY, 'token' => $token); $token = ''; $stack->pop(); } } elseif ($char === ' ') { $tokens[] = array('code' => SOAP_WHITESPACE, 'token' => $char); } break; } } return $tokens; }
/** * @param array[array|string|int] $args * @return void */ public function stack(array $args) { $stack = new \Stack(); $stack->push("test"); $stack->push("test2"); var_dump($stack->getArray()); $this->response->outLine($stack->pop()); $this->response->outLine($stack->pop()); }
private function pushIfNotNull($direction, BinaryTree $n) { $next = $n->{$direction}(); if ($next !== null) { $this->stack->push($next); } }
/** * register a class for startup * @param string $classname * @param bool $useDI */ public static function add($classname, $useDI = false) { if (is_array(self::$startup) && is_array(self::$DIstartup)) { if ($useDI) { self::$DIstartup[] = $classname; } else { self::$startup[] = $classname; } } else { if ($useDI) { self::$DIstartup->push($classname); } else { self::$startup->push($classname); } } }
public static function postfixArray($s) { $stack = new Stack(); for ($i = 0; $i < count($s); $i++) { $item = $s[$i]; if ($item->type == "Integer" || $item->type == "Variable") { $stack->push($item); } else { $tree = new Tree(); $tree->operator = $item; $tree->right = $stack->pop(); $tree->left = $stack->pop(); $stack->push($tree); } } return $stack->pop(); }
public function testInsertAndRemove() { $Stack = new Stack(); $Stack->push('Radig'); $this->assertIdentical($Stack->size(), 1); $this->assertIdentical($Stack->nth(), 'Radig'); $Stack->push('CakePHP'); $this->assertIdentical($Stack->size(), 2); // testa com 1-lookahead $this->assertIdentical($Stack->nth(), 'CakePHP'); // teste com 2-lookahead $this->assertIdentical($Stack->nth(2), 'Radig'); $this->assertIdentical($Stack->pop(), 'CakePHP'); $this->assertIdentical($Stack->pop(), 'Radig'); $this->assertIdentical($Stack->pop(), null); unset($Stack); }
public function testALL() { $this->assertTrue($this->object->count() == 10); $this->assertTrue($this->object->pop()->toNative() == 9); $this->assertTrue($this->object->count() == 9); $this->object->push(1); $this->assertTrue($this->object->remove(1)); $this->object->push(78); }
public function testStack() { $stack = new Stack(); $this->assertEquals(0, $stack->length()); $stack->push('foo'); $this->assertEquals('foo', $stack->peek()); $this->assertEquals(1, $stack->length()); $this->assertEquals('foo', $stack->pop()); $this->assertEquals(0, $stack->length()); }
/** * Definice vlastního písma * * @return bool */ protected function atFontFace() { $x = $this->getOffset(); if (($this->getActualBlock() instanceof Main || $this->getActualBlock() instanceof Media || $this->getActualBlock() instanceof Mixin) && $this->char('@font-face') && $this->char('{')) { $block = new FontFace(); $this->getActualBlock()->properties[] = $block; $this->stack->push($block); return TRUE; } $this->setOffset($x); return FALSE; }
public static function testStructure() { $stack = new Stack(); if ($stack->getCount() !== 0) { self::printError("problem creating a new stack - count not 0"); } // test push $stack->push('push1'); $stack->push('push2'); $stack->push('push3'); $stack->push('push4'); $stack->push('push5'); $stack->push('push6'); if ($stack->getCount() !== 6) { self::printError("problem pushing to stack - count not 6"); } // test pop $data1 = $stack->pop(); if ($data1 !== 'push6') { self::printError("problem popping from stack - wrong item found"); } if ($stack->getCount() !== 5) { self::printError("problem popping from stack - count not 5"); } // display... for now $stack->display(); }
public function expression($str) { $input = new Stack(); $output = new Stack(); foreach ($this->tokenizer->tokenize($str) as $token) { $part = Dictionary::fromString($token); $part->isOperator() ? $input->push($part) : $output->push($part); } while ($operator = $input->pop()) { $output->push($operator); } // Ran out of time, this'll only work with addition $op = $output->pop(); $val = $op->operate($output); return $val; }
public $item; public $next; } class Stack { private $first = null; public function isEmpty() { return $this->first == null; } public function push($item) { $oldfirst = $this->first; $this->first = new Node(); $this->first->item = $item; $this->first->next = $oldfirst; } public function pop() { $item = $this->first->item; $this->first = $this->first->next; return $item; } } $list = new Stack(); $list->push(1); $list->push(2); $list->push(3); echo $list->pop(); echo $list->pop(); echo $list->pop();
/** * Infix to Postfix * * Converts an infix (standard) equation to postfix (RPN) notation. * Sets the internal variable $this->postFix for the Parser::solvePF() * function to use. * * @link http://en.wikipedia.org/wiki/Infix_notation Infix Notation * @link http://en.wikipedia.org/wiki/Reverse_Polish_notation Reverse Polish Notation * @param String $infix A standard notation equation * @throws \Exception When parenthesis are mismatched * @return Array Fully formed RPN Stack */ public static function in2post($infix) { // if an equation was not passed, use the one that was passed in the constructor //$infix = (isset($infix)) ? $infix : $this->inFix; //check to make sure 'valid' equation self::checkInfix($infix); $pf = array(); $ops = new Stack(); //$vars = new Stack(); // remove all white-space $infix = preg_replace("/\\s/", "", $infix); // Create postfix array index $pfIndex = 0; //what was the last character? (useful for discerning between a sign for negation and subtraction) $lChar = ''; //loop through all the characters and start doing stuff ^^ for ($i = 0; $i < strlen($infix); $i++) { // pull out 1 character from the string $chr = substr($infix, $i, 1); // if the character is numerical if (preg_match('/[0-9.]/i', $chr)) { // if the previous character was not a '-' or a number if (!preg_match('/[0-9.]/i', $lChar) && $lChar != "" && (isset($pf[$pfIndex]) && $pf[$pfIndex] != "-")) { $pfIndex++; } // increase the index so as not to overlap anything // Add the number character to the array if (isset($pf[$pfIndex])) { $pf[$pfIndex] .= $chr; } else { $pf[$pfIndex] = $chr; } } elseif (in_array($chr, self::$SEP['open'])) { // if the last character was a number, place an assumed '*' on the stack if (preg_match('/[0-9.]/i', $lChar)) { $ops->push('*'); } $ops->push($chr); } elseif (in_array($chr, self::$SEP['close'])) { // find what set it was i.e. matches ')' with '(' or ']' with '[' $key = array_search($chr, self::$SEP['close']); // while the operator on the stack isn't the matching pair...pop it off while ($ops->peek() != self::$SEP['open'][$key]) { $nchr = $ops->pop(); if ($nchr) { $pf[++$pfIndex] = $nchr; } else { throw new \Exception("Error while searching for '" . self::$SEP['open'][$key] . "' in " . self::$inFix, Math::E_NO_SET); } } $ops->pop(); } elseif (in_array($chr, self::$ST)) { while (in_array($ops->peek(), self::$ST)) { $pf[++$pfIndex] = $ops->pop(); } $ops->push($chr); $pfIndex++; } elseif (in_array($chr, self::$ST1)) { while (in_array($ops->peek(), self::$ST1) || in_array($ops->peek(), self::$ST)) { $pf[++$pfIndex] = $ops->pop(); } $ops->push($chr); $pfIndex++; } elseif (in_array($chr, self::$ST2)) { // if it is a '-' and the character before it was an operator or nothingness (e.g. it negates a number) if ((in_array($lChar, array_merge(self::$ST1, self::$ST2, self::$ST, self::$SEP['open'])) || $lChar == "") && $chr == "-") { // increase the index because there is no reason that it shouldn't.. $pfIndex++; $pf[$pfIndex] = $chr; } else { while (in_array($ops->peek(), array_merge(self::$ST1, self::$ST2, self::$ST))) { $pf[++$pfIndex] = $ops->pop(); } $ops->push($chr); $pfIndex++; } } // make sure we record this character to be referred to by the next one $lChar = $chr; } // if there is anything on the stack after we are done...add it to the back of the RPN array while (($tmp = $ops->pop()) !== false) { $pf[++$pfIndex] = $tmp; } // re-index the array at 0 $pf = array_values($pf); // set the private variable for later use if needed //self::$postFix = $pf; // return the RPN array in case developer wants to use it for some insane reason (bug testing ;] ) // Also... because we pass it right in to the RPN solver. So I guess there's that too. return $pf; }
private function process() { //echo "Processing postfix notation:\n\n"; $tempStack = new Stack(); while ($token = $this->rpnNotation->dequeue()) { if ($token instanceof Number) { $tempStack->push($token); } elseif ($token instanceof Operator || $token instanceof Funct) { /** @var $token Operator|Funct */ if ($tempStack->count() < $token->numOfArgs()) { throw new Exception(sprintf('Required %d arguments, %d given.', $token->numOfArgs(), $tempStack->count())); } $arg = $tempStack->popMultiple($token->numOfArgs()); $tempStack->push($token->execute(array_reverse($arg))); } } return $tempStack->pop()->value; }
function calculate_polish_notation($notation) { $calc_stack = new Stack(); for ($i = 0; $i < strlen($notation); $i++) { $current_number = ''; if ($notation[$i] == '.') { ++$i; do { $current_number .= $notation[$i]; } while (is_numeric($notation[++$i])); --$i; $calc_stack->push($current_number); $current_number = ''; } if ($notation[$i] == '-' or $notation[$i] == '+' or $notation[$i] == '*' or $notation[$i] == '/' or $notation[$i] == '^') { $a = $calc_stack->pop(); $b = $calc_stack->pop(); if ($notation[$i] == '-') { $result = $b - $a; } elseif ($notation[$i] == '+') { $result = $a + $b; } elseif ($notation[$i] == '*') { $result = $a * $b; } elseif ($notation[$i] == '/') { if ($a == 0) { show_error('В выражении возникло деление на ноль.'); return; } else { $result = $b / $a; } } elseif ($notation[$i] == '^') { $result = pow($b, $a); } $calc_stack->push($result); } } return $result; }
/** * Converts stack collection to string output. */ public function __toString() { if ($this->isEmpty()) { $itemsString = 'Stack is empty.'; } else { $itemsString = implode(', ', $this->items); } $itemsString .= PHP_EOL; return $itemsString; } } $stack = new Stack(); $stack->push('A'); echo (string) $stack; // A $stack->pop(); echo (string) $stack; // Stack is empty. $stack->pop(); echo (string) $stack; // Stack is empty. $stack->push('B'); echo (string) $stack; // B $stack->push('C'); echo (string) $stack; // B, C $stack->push('D');
private function pushLeft(BinaryTree $n = null) { for ($current = $n; $current !== null; $current = $current->left()) { $this->stack->push($current); } }
public function get_pilha() { $pilha = new Stack(); $pilha->push($this->getElemento()); $node = $this->parent_node; if ($node) { do { $pilha->push($node->getElemento()); $node = $node->parent_node; } while ($node); } return $pilha; }
/** * Evaluate postfix notation * * @param array $tokens * @param array $vars * * @return mixed boolean *false* in failures and *numeric* value in success */ protected function pfx($tokens, $vars = array()) { bcscale($this->precision); if ($tokens === false) { return false; } $stack = new Stack(); foreach ($tokens as $token) { // if the token is a binary operator, pop two values off the stack, do the operation, and push the result back on if (in_array($token, array('+', '-', '*', '/', '^'))) { if (is_null($op2 = $stack->pop()) || is_null($op1 = $stack->pop())) { return $this->error("Internal error"); } switch ($token) { case '+': $stack->push(bcadd($op1, $op2)); break; case '-': $stack->push(bcsub($op1, $op2)); break; case '*': $stack->push(bcmul($op1, $op2)); break; case '/': if ($op2 == 0) { return $this->error("Division by zero"); } $stack->push(bcdiv($op1, $op2)); break; case '^': $stack->push(bcpow($op1, $op2)); break; } // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on } elseif ($token == "_") { // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on $stack->push(-1 * $stack->pop()); } elseif (preg_match("/^([a-z]\\w*)\\(\$/", $token, $matches)) { // it's a function! $fnn = $matches[1]; // built-in function: if (in_array($fnn, $this->fb)) { if (is_null($op1 = $stack->pop())) { return $this->error("Internal error"); } // for the 'arc' trig synonyms $fnn = preg_replace("/^arc/", "a", $fnn); if ($fnn == 'ln') { $fnn = 'log'; } if ($fnn == 'sqrt') { $fnn = 'bcsqrt'; } $val = $this->strictPrecision(call_user_func($fnn, $op1)); $stack->push($val); } elseif (array_key_exists($fnn, $this->f)) { // get args $args = array(); for ($i = count($this->f[$fnn]['args']) - 1; $i >= 0; $i--) { if (is_null($args[$this->f[$fnn]['args'][$i]] = $stack->pop())) { return $this->error("Internal error"); } } $stack->push($this->pfx($this->f[$fnn]['func'], $args)); // yay... recursion!!!! } } else { if (is_numeric($token)) { $stack->push($this->strictPrecision($token)); } elseif (array_key_exists($token, $this->v)) { $stack->push($this->strictPrecision($this->v[$token])); } elseif (array_key_exists($token, $vars)) { $stack->push($this->strictPrecision($vars[$token])); } else { return $this->error("Undefined variable '{$token}'"); } } } // when we're out of tokens, the stack should have a single element, the final result if ($stack->size() != 1) { return $this->error("Internal error"); } return $stack->pop(); }
private function next_push(BinaryTree $n = null) { $this->stack->push($this->value); $this->value = $n; $this->next(); }
public function pfx($tokens, $vars = array()) { if ($tokens == false) { return false; } $stack = new Stack(); foreach ($tokens as $token) { // nice and easy // if the token is a binary operator, pop two values off the stack, do the operation, and push the result back on if (in_array($token, array('+', '-', '*', '/', '^'))) { if (is_null($op2 = $stack->pop())) { return $this->trigger("internal error"); } if (is_null($op1 = $stack->pop())) { return $this->trigger("internal error"); } switch ($token) { case '+': $stack->push($op1 + $op2); break; case '-': $stack->push($op1 - $op2); break; case '*': $stack->push($op1 * $op2); break; case '/': if ($op2 == 0) { return $this->trigger("division by zero"); } $stack->push($op1 / $op2); break; case '^': $stack->push(pow($op1, $op2)); break; } // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on } elseif ($token == "_") { $stack->push(-1 * $stack->pop()); // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on } elseif (preg_match("/^([a-z]\\w*)\\(\$/", $token, $matches)) { // it's a function! $fnn = $matches[1]; if (in_array($fnn, $this->fb)) { // built-in function: if (is_null($op1 = $stack->pop())) { return $this->trigger("internal error"); } $fnn = preg_replace("/^arc/", "a", $fnn); // for the 'arc' trig synonyms if ($fnn == 'ln') { $fnn = 'log'; } eval('$stack->push(' . $fnn . '($op1));'); // perfectly safe eval() } elseif (array_key_exists($fnn, $this->f)) { // user function // get args $args = array(); for ($i = count($this->f[$fnn]['args']) - 1; $i >= 0; $i--) { if (is_null($args[$this->f[$fnn]['args'][$i]] = $stack->pop())) { return $this->trigger("internal error"); } } $stack->push($this->pfx($this->f[$fnn]['func'], $args)); // yay... recursion!!!! } // if the token is a number or variable, push it on the stack } else { if (is_numeric($token)) { $stack->push($token); } elseif (array_key_exists($token, $this->v)) { $stack->push($this->v[$token]); } elseif (array_key_exists($token, $vars)) { $stack->push($vars[$token]); } else { return $this->trigger("undefined variable '{$token}'"); } } } // when we're out of tokens, the stack should have a single element, the final result if ($stack->count != 1) { return $this->trigger("internal error"); } return $stack->pop(); }
class Stack { private $data = array(); public function push($element) { $this->data[] = $element; } public function pop() { if ($this->isEmpty()) { return null; } return array_pop($this->data); } public function isEmpty() { return count($this->data) == 0; } } foreach (file($argv[1]) as $line) { $stack = new Stack(); foreach (explode(" ", trim($line)) as $number) { $stack->push($number); } $toPrint = array(); while (!$stack->isEmpty()) { $toPrint[] = $stack->pop(); $stack->pop(); } echo implode(" ", $toPrint) . "\n"; }
if ($this->index == -1) { return true; } return false; } public function pop() { if (!$this->isEmpty()) { $element = $this->stackArray[$this->index]; unset($this->stackArray[$this->index]); $this->index--; return $element; } return "your stack is empty"; } public function first() { return $this->stackArray[$this->index]; } public function last() { return $this->stackArray[0]; } } $mystack = new Stack(); $mystack->push(1); $mystack->push(4); //echo "first is : ".$mystack->first()."<br>"; //echo "last is : ".$mystack->last()."<br>"; //echo "1st pop is :".$mystack->pop()."<br>"; //echo "2nd pop is : ".$mystack->pop();
<?php namespace struct; include 'Stack.php'; $myBooks = new Stack(); $myBooks->push('Игра престолов'); $myBooks->push('99 франков'); $myBooks->push('Девушка с татуировкой дракона'); $myBooks->push('Цветы для Элджернона'); foreach ($myBooks as $book) { print $book . PHP_EOL; }
<?php //include "C:/xampp/htdocs/LearningPHP/PHP/myFunction/explode_functions.php"; include "C:/xampp/htdocs/Training/PHP/functions.php"; include "stack2.php"; if (isset($_POST['exp'])) { $expression = $_POST['exp']; $expArray = explode(" ", $expression); echo "<pre>"; print_r($expArray); echo "</pre>"; $myStack = new Stack(); foreach ($expArray as $op) { $temp = intval($op); if ($temp) { $myStack->push($temp); echo "<pre>"; print_r($myStack); echo "</pre>"; } else { $op2 = $myStack->pop(); $op1 = $myStack->pop(); echo "<br>", $op1, " ", $op2, " ", $op, "<br>"; $result = calculator($op1, $op2, $op); echo "<br>", $result, "<br>"; $myStack->push($result); echo "<pre>"; print_r($myStack); echo "</pre>"; } }
} else { echo "stack is empty"; } } public function isEmpty() { if ($this->index == -1) { return true; } else { return false; } } public function first() { echo $this->stackArray[$this->index]; } public function last() { echo $this->stackArray[0]; } } $newStack = new Stack(); $newStack->push(2); $newStack->push(6); $newStack->pop(); $newStack->pop(); $newStack->pop(); $newStack->isEmpty(); $newStack->first(); $newStack->last(); $newStack->getElement(1);
} else { return false; } } function First() { return $this->stackArray[$this->index]; } function Last() { return $this->stackArray[0]; } public function getElement($position) { if ($position <= $this->index + 1) { $arrayPosition = $this->index + 1 - $position; return $this->stackArray[$arrayPosition]; } else { echo "Invalid"; } } } $myStack = new Stack(); $myStack->push(1); $myStack->push(4); $myStack->push(5); echo "First pop is ", $myStack->pop(), "<br>"; echo "Second pop is ", $myStack->pop(), "<br>"; echo "First value of stack is ", $myStack->First(), "<br>"; $myStack->pop(); echo "present index value is ", $myStack->getElement(2);
public function push($item) { if ($item == $this->peek()) { parent::push($item); } else { throw new LogicException("EqStack::push(): unequal item."); } }
protected function parseOperator(TerminalExpression $expression, Stack $output, Stack $operators) { $end = $operators->poke(); if (!$end) { $operators->push($expression); } elseif (!$expression->isUnary() && $end->isOperator()) { do { if ($expression->isLeftAssoc() && $expression->getPrecedence() <= $end->getPrecedence()) { $output->push($operators->pop()); } elseif (!$expression->isLeftAssoc() && $expression->getPrecedence() < $end->getPrecedence()) { $output->push($operators->pop()); } else { break; } } while (($end = $operators->poke()) && $end->isOperator()); $operators->push($expression); } elseif ($expression->isUnary() && $end->isUnary()) { if ($expression->isNegative() == $end->isNegative()) { //very intruiging $operators->pop(); } elseif ($expression->isNegative()) { $operators->pop(); $operators->push($expression); } } else { $operators->push($expression); } }
<?php include "C:/xampp/htdocs/training/php/OOP/myFunction/function.php"; include "C:/xampp/htdocs/training/php/OOP/myFunction/stack_oop.php"; include "C:/xampp/htdocs/training/php/OOP/myFunction/explode_functions.php"; $expression = "4 65 - 3 71 - +"; $exparr = explode(" ", $expression); /*echo "<pre>"; print_r($exparr); echo "</pre>";*/ $myStack = new Stack(); foreach ($exparr as $operator) { $temp = intval($operator); if ($temp) { $myStack->push($temp); /* echo "<pre>"; print_r($myStack); echo "</pre>"; */ } else { $op2 = $myStack->pop(); $op1 = $myStack->pop(); //echo "<br>",$op1," ",$op2," ",$operator,"<br>"; $result = calculator($op1, $op2, $operator); //echo $result; $myStack->push($result); } } echo "my result is :", $myStack->pop();