Last active
February 26, 2022 01:17
-
-
Save nnnikolay/b0547efe20381e57f3820ffb62554631 to your computer and use it in GitHub Desktop.
One of the codility task implemented by me (Word machine with capability add, duplicate, pop, sum and subtract from the stack)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function solution($S) | |
{ | |
$stack = []; | |
foreach(parseCommand($S) as $command) { | |
try { | |
$stack = performOperation($command)($stack); | |
} catch (Exception $e) { | |
return -1; | |
} | |
} | |
return $stack; | |
} | |
function parseCommand($string) | |
{ | |
return explode(' ', $string); | |
} | |
function performOperation($command) | |
{ | |
return function($stack) use ($command) { | |
$newStack = $stack; | |
switch($command) { | |
case is_numeric($command): | |
array_push($newStack, $command); | |
break; | |
case "DUP": | |
array_push($newStack, end($stack)); | |
break; | |
case "POP": | |
array_pop($newStack); | |
break; | |
case "+": | |
$lastElement = array_pop($newStack); | |
$preLastElement = array_pop($newStack); | |
array_push($newStack, $lastElement + $preLastElement); | |
break; | |
case "-": | |
$lastElement = array_pop($newStack); | |
$preLastElement = array_pop($newStack); | |
if ($preLastElement === null || ($lastElement - $preLastElement) < 0) { | |
throw new Exception('Not enough items in a stack'); | |
} | |
array_push($newStack, $lastElement - $preLastElement); | |
break; | |
} | |
return $newStack; | |
}; | |
} | |
print_r(solution('3 3 2 DUP POP + -')); // result is 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment