Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $numbers = array(5, 19, 45, 6, 7, 21);
- $operators = array('*', '+', '-', '*', '+');
- // String bauen
- $mathString = '';
- foreach ($numbers as $id => $number) {
- if ($id < count($numbers)-1) {
- $mathString .= $number . $operators[$id];
- } else {
- $mathString .= $number;
- }
- }
- // $mathString ist nun '5*19+45-6*7+21'
- ##################################
- function flatten($ms, $ops) {
- $list = array();
- $len = strlen($ms);
- $buf = '';
- for ($i=0;$i<$len;$i++) {
- $chr = $ms[$i];
- if (!array_key_exists($chr, $ops)) {
- $buf .= $chr;
- } else {
- $list[] = $buf;
- $list[] = $chr;
- $buf = '';
- }
- }
- $list[] = $buf;
- return $list;
- }
- function apply($list, $ops) {
- $o = $list[1];
- $func = $ops[$o];
- $h = $func($list[0], $list[2]);
- return $h;
- }
- function foldl($list, $ops, $prio) {
- if (!isset($list[2])) {
- return $list[0];
- } else {
- $o = $list[1];
- if (in_array($o, $prio)) {
- $h = apply($list, $ops);
- $t = array_slice($list, 3);
- array_unshift($t, $h);
- return foldl($t, $ops, $prio);
- } else {
- if (isset($list[3])) {
- $look = $list[3];
- if (in_array($look, $prio)) {
- $tmp = array_slice($list, 2, 3);
- $m = apply($tmp, $ops);
- if (isset($list[5])) {
- $t = array_slice($list, 5);
- } else {
- $t = array();
- }
- $li = array_unshift($t, $list[0], $list[1], $m);
- return foldl($t, $ops, $prio);
- } else {
- $h = apply($list, $ops);
- $t = array_slice($list, 3);
- array_unshift($t, $h);
- return foldl($t, $ops, $prio);
- }
- } else {
- $h = apply($list, $ops);
- return foldl(array($h), $ops, $prio);
- }
- }
- }
- }
- // prio der abarbeitung
- $prio = array('*');
- // closures, whee
- $ops = array(
- '*' => function($a,$b) { return $a * $b; },
- '+' => function($a,$b) { return $a + $b; },
- '-' => function($a,$b) { return $a - $b; },
- );
- $list = flatten($mathString, $ops);
- echo $mathString.PHP_EOL;
- var_dump($list);
- $r = foldl($list, $ops, $prio, array());
- echo "----\nresult: $r".PHP_EOL;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement