Created
December 29, 2014 16:12
-
-
Save rocketeerbkw/d1098613ea6cc5312319 to your computer and use it in GitHub Desktop.
This file contains 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 | |
$text = <<<EOF | |
EOF; | |
$problems = array(); | |
$solutions = array(); | |
preg_match_all('/^(.*)$/m', $text, $problems); | |
foreach ($problems[0] as $problem) { | |
$prefix = convert_to_prefix($problem); | |
echo $prefix . PHP_EOL; | |
$rprefix = explode(' ', $prefix); | |
$solution = rpn(array_reverse($rprefix)); | |
echo $solution . PHP_EOL; | |
$solutions[] = $solution; | |
} | |
foreach ($solutions as $solutions) { | |
echo chr($solutions); | |
} | |
function convert_to_prefix($string) { | |
echo $string . PHP_EOL; | |
$pnotation = $string; | |
$pnotation = preg_replace('/\b3 5\b/', '+', $pnotation); | |
$pnotation = preg_replace('/\b3 6\b/', '-', $pnotation); | |
$pnotation = preg_replace('/\b3 7\b/', '/', $pnotation); | |
$pnotation = preg_replace('/\b1 (\d+)\b/', '$1', $pnotation); | |
$pnotation = preg_replace('/\b2 (\d+)\b/', '-$1', $pnotation); | |
return $pnotation; | |
} | |
// https://gist.github.com/rhrn/3705119 | |
function rpn($params) { | |
$count = sizeof($params); | |
$result = null; | |
$numeric = array(); | |
for($i = 0; $i < $count; $i++) { | |
if (is_numeric($params[$i])) { | |
$numeric[] = $params[$i]; | |
} else { | |
switch ($params[$i]) { | |
case "+": | |
$result = array_pop($numeric) + array_pop($numeric); | |
break; | |
case "-": | |
$result = array_pop($numeric) - array_pop($numeric); | |
break; | |
case "*": | |
$result = array_pop($numeric) * array_pop($numeric); | |
break; | |
case "/": | |
$result = array_pop($numeric) / array_pop($numeric); | |
break; | |
} | |
array_push($numeric, $result); | |
} | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment