-
Notifications
You must be signed in to change notification settings - Fork 7
/
PostfixStuff.java
121 lines (114 loc) · 2.65 KB
/
PostfixStuff.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import java.util.*;
public class PostfixStuff {
public static void main(String[] args) throws Exception {
String eq = "4 1 2 9 3 / * + 5 - *";
double res = postfixCalculator(eq);
System.out.println(res);
eq = "4 * ( 1 + 2 * ( 9 / 3 ) - 5 )";
String ret = shuntingYard(eq);
System.out.println(ret);
}
//returns an infix expression in postfix notation.
static String shuntingYard(String eq) {
String[] split = eq.split("\\s+");
Stack<String> s = new Stack<>();
StringBuilder res = new StringBuilder();
for(int i = 0; i < split.length; i++) {
if(isNum(split[i])) {
res.append(split[i] + " ");
} else {
switch(split[i]) {
case ")":
while(!s.isEmpty()) {
String now = s.pop();
if(now.equals("(")) break;
res.append(now + " ");
}
break;
case "(":
s.push(split[i]);
break;
default:
int p = precedence(split[i]);
while(!s.isEmpty()) {
String str = s.peek();
int p2 = precedence(str);
if(p2 >= p) {
res.append(str + " ");
s.pop();
} else break;
}
s.push(split[i]);
break;
}
}
}
while(!s.isEmpty()) res.append(s.pop() + " ");
return res.toString().trim();
}
static int precedence(String s) {
switch(s) {
case "+":
case "-":
return 1;
case "*":
case "/":
return 2;
case "^":
return 3;
}
return -1;
}
private static boolean isNum(String string) {
for(int i = 0; i < string.length(); i++) {
if(Character.isDigit(string.charAt(i)) == false) return false;
}
return true;
}
//returns the value of a function in Postfix notation
//String passed must be in postfix notation
//to evaluate a function in prefix notation, do this method but read the string backwards.
static double postfixCalculator(String eq) {
String[] split = eq.split("\\s+");
Stack<String> s = new Stack<>();
for(int i = 0; i < split.length; i++) {
int val;
if((val = isOperator(split[i])) > 0) {
double push = 0;
double n2 = Double.parseDouble(s.pop());
double n1 = Double.parseDouble(s.pop());
switch(val) {
case 1:
push = n1 + n2;
break;
case 2:
push = n1 / n2;
break;
case 3:
push = n1 * n2;
break;
case 4:
push = n1 - n2;
break;
}
s.push(push + "");
} else {
s.push(split[i]);
}
}
return Double.parseDouble(s.pop());
}
private static int isOperator(String string) {
switch(string) {
case "+":
return 1;
case "/":
return 2;
case "*":
return 3;
case "-":
return 4;
}
return -1;
}
}