1.
1 package algorithms.util; 2 3 import algorithms.ADT.Stack; 4 5 /****************************************************************************** 6 * Compilation: javac Evaluate.java 7 * Execution: java Evaluate 8 * Dependencies: Stack.java 9 * 10 * Evaluates (fully parenthesized) arithmetic expressions using 11 * Dijkstra's two-stack algorithm. 12 * 13 * % java Evaluate 14 * ( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) ) 15 * 101.0 16 * 17 * % java Evaulate 18 * ( ( 1 + sqrt ( 5 ) ) / 2.0 ) 19 * 1.618033988749895 20 * 21 * 22 * Note: the operators, operands, and parentheses must be 23 * separated by whitespace. Also, each operation must 24 * be enclosed in parentheses. For example, you must write 25 * ( 1 + ( 2 + 3 ) ) instead of ( 1 + 2 + 3 ). 26 * See EvaluateDeluxe.java for a fancier version. 27 * 28 * 29 * Remarkably, Dijkstra's algorithm computes the same 30 * answer if we put each operator *after* its two operands 31 * instead of *between* them. 32 * 33 * % java Evaluate 34 * ( 1 ( ( 2 3 + ) ( 4 5 * ) * ) + ) 35 * 101.0 36 * 37 * Moreover, in such expressions, all parentheses are redundant! 38 * Removing them yields an expression known as a postfix expression. 39 * 1 2 3 + 4 5 * * + 40 * 41 * 42 ******************************************************************************/ 43 44 public class Evaluate { 45 public static void main(String[] args) { 46 Stack<String> ops = new Stack<String>(); 47 Stack<Double> vals = new Stack<Double>(); 48 49 while (!StdIn.isEmpty()) { 50 String s = StdIn.readString(); 51 if (s.equals("(")) ; 52 else if (s.equals("+")) ops.push(s); 53 else if (s.equals("-")) ops.push(s); 54 else if (s.equals("*")) ops.push(s); 55 else if (s.equals("/")) ops.push(s); 56 else if (s.equals("sqrt")) ops.push(s); 57 else if (s.equals(")")) { 58 String op = ops.pop(); 59 double v = vals.pop(); 60 if (op.equals("+")) v = vals.pop() + v; 61 else if (op.equals("-")) v = vals.pop() - v; 62 else if (op.equals("*")) v = vals.pop() * v; 63 else if (op.equals("/")) v = vals.pop() / v; 64 else if (op.equals("sqrt")) v = Math.sqrt(v); 65 vals.push(v); 66 } 67 else vals.push(Double.parseDouble(s)); 68 } 69 StdOut.println(vals.pop()); 70 } 71 }