Another update from ingydotnet^djgoku

This commit is contained in:
Ingy döt Net 2015-11-18 06:14:39 +00:00
parent 91df62d461
commit 948b86eafa
7604 changed files with 108452 additions and 22726 deletions

View file

@ -14,11 +14,16 @@ public class ShuntingYard {
Stack<Integer> s = new Stack<>();
for (String token : infix.split("\\s")) {
if (token.isEmpty())
continue;
char c = token.charAt(0);
int idx = ops.indexOf(c);
if (idx != -1 && token.length() == 1) {
// check for operator
if (idx != -1) {
if (s.isEmpty())
s.push(idx);
else {
while (!s.isEmpty()) {
int prec2 = s.peek() / 2;
@ -29,13 +34,17 @@ public class ShuntingYard {
}
s.push(idx);
}
} else if (c == '(') {
s.push(-2);
} else if (c == ')') {
}
else if (c == '(') {
s.push(-2); // -2 stands for '('
}
else if (c == ')') {
// until '(' on stack, pop operators.
while (s.peek() != -2)
sb.append(ops.charAt(s.pop())).append(' ');
s.pop();
} else {
}
else {
sb.append(token).append(' ');
}
}

View file

@ -0,0 +1,32 @@
rpn[str_] :=
StringRiffle[
ToString /@
Module[{in = StringSplit[str], stack = {}, out = {}, next},
While[in != {}, next = in[[1]]; in = in[[2 ;;]];
Which[DigitQ[next], AppendTo[out, next], LetterQ[next],
AppendTo[stack, next], next == ",",
While[stack[[-1]] != "(", AppendTo[out, stack[[-1]]];
stack = stack[[;; -2]]], next == "^", AppendTo[stack, "^"],
next == "*",
While[stack != {} && MatchQ[stack[[-1]], "^" | "*" | "/"],
AppendTo[out, stack[[-1]]]; stack = stack[[;; -2]]];
AppendTo[stack, "*"], next == "/",
While[stack != {} && MatchQ[stack[[-1]], "^" | "*" | "/"],
AppendTo[out, stack[[-1]]]; stack = stack[[;; -2]]];
AppendTo[stack, "/"], next == "+",
While[stack != {} &&
MatchQ[stack[[-1]], "^" | "*" | "/" | "+" | "-"],
AppendTo[out, stack[[-1]]]; stack = stack[[;; -2]]];
AppendTo[stack, "+"], next == "-",
While[stack != {} &&
MatchQ[stack[[-1]], "^" | "*" | "/" | "+" | "-"],
AppendTo[out, stack[[-1]]]; stack = stack[[;; -2]]];
AppendTo[stack, "-"], next == "(", AppendTo[stack, "("],
next == ")",
While[stack[[-1]] =!= "(", AppendTo[out, stack[[-1]]];
stack = stack[[;; -2]]]; stack = stack[[;; -2]];
If[StringQ[stack[[-1]]], AppendTo[out, stack[[-1]]];
stack = stack[[;; -2]]]]];
While[stack != {}, AppendTo[out, stack[[-1]]];
stack = stack[[;; -2]]]; out]];
Print[rpn["3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"]];