Advertisement
Guest User

RPN no filereading

a guest
Nov 17th, 2012
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.50 KB | None | 0 0
  1. import java.util.*;  
  2.    
  3. public class ExpressionParser  
  4. {  
  5.     // Associativity constants for operators  
  6.     private static final int LEFT_ASSOC  = 0;  
  7.     private static final int RIGHT_ASSOC = 1;  
  8.    
  9.     // Operators  
  10.     private static final Map<String, int[]> OPERATORS = new HashMap<String, int[]>();  
  11.     static  
  12.     {  
  13.         // Map<"token", []{precendence, associativity}>  
  14.         OPERATORS.put("+", new int[] { 0, LEFT_ASSOC });  
  15.         OPERATORS.put("-", new int[] { 0, LEFT_ASSOC });  
  16.         OPERATORS.put("*", new int[] { 5, LEFT_ASSOC });  
  17.         OPERATORS.put("/", new int[] { 5, LEFT_ASSOC });          
  18.     }  
  19.    
  20.     // Test if token is an operator  
  21.     private static boolean isOperator(String token)  
  22.     {  
  23.         return OPERATORS.containsKey(token);  
  24.     }  
  25.    
  26.     // Test associativity of operator token  
  27.     private static boolean isAssociative(String token, int type)  
  28.     {  
  29.         if (!isOperator(token))  
  30.         {  
  31.             throw new IllegalArgumentException("Invalid token: " + token);  
  32.         }  
  33.          
  34.         if (OPERATORS.get(token)[1] == type) {  
  35.             return true;  
  36.         }  
  37.         return false;  
  38.     }  
  39.    
  40.     // Compare precedence of operators.      
  41.     private static final int cmpPrecedence(String token1, String token2)  
  42.     {  
  43.         if (!isOperator(token1) || !isOperator(token2))  
  44.         {  
  45.             throw new IllegalArgumentException("Invalid tokens: " + token1  
  46.                     + " " + token2);  
  47.         }  
  48.         return OPERATORS.get(token1)[0] - OPERATORS.get(token2)[0];  
  49.     }  
  50.    
  51.     // Convert infix expression format into reverse Polish notation  
  52.     public static String[] infixToRPN(String[] inputTokens)  
  53.     {  
  54.         ArrayList<String> out = new ArrayList<String>();  
  55.         myStack<String> stack = new myStack<String>();  
  56.          
  57.         // For each token  
  58.         for (String token : inputTokens)  
  59.         {  
  60.             // If token is an operator  
  61.             if (isOperator(token))  
  62.             {    
  63.                 // While stack not empty AND stack top element  
  64.                 // is an operator  
  65.                 while (!stack.empty() && isOperator(stack.peek()))  
  66.                 {                      
  67.                     if ((isAssociative(token, LEFT_ASSOC)         &&  
  68.                          cmpPrecedence(token, stack.peek()) <= 0) ||  
  69.                         (isAssociative(token, RIGHT_ASSOC)        &&  
  70.                          cmpPrecedence(token, stack.peek()) < 0))  
  71.                     {  
  72.                         out.add(stack.pop());    
  73.                         continue;  
  74.                     }  
  75.                     break;  
  76.                 }  
  77.                 // Push the new operator on the stack  
  78.                 stack.push(token);  
  79.             }  
  80.             // If token is a left bracket '('  
  81.             else if (token.equals("("))  
  82.             {  
  83.                 stack.push(token);  //  
  84.             }  
  85.             // If token is a right bracket ')'  
  86.             else if (token.equals(")"))  
  87.             {                  
  88.                 while (!stack.empty() && !stack.peek().equals("("))  
  89.                 {  
  90.                     out.add(stack.pop());  
  91.                 }  
  92.                 stack.pop();  
  93.             }  
  94.             // If token is a number  
  95.             else  
  96.             {  
  97.                 out.add(token);  
  98.             }  
  99.         }  
  100.         while (!stack.empty())  
  101.         {  
  102.             out.add(stack.pop());  
  103.         }  
  104.         String[] output = new String[out.size()];  
  105.         return out.toArray(output);  
  106.     }  
  107.      
  108.     public static double RPNtoDouble(String[] tokens)  
  109.     {          
  110.         Stack<String> stack = new Stack<String>();  
  111.          
  112.         // For each token  
  113.         for (String token : tokens)  
  114.         {  
  115.             // If the token is a value push it onto the stack  
  116.             if (!isOperator(token))  
  117.             {  
  118.                 stack.push(token);                  
  119.             }  
  120.             else  
  121.             {  
  122.                 // Token is an operator: pop top two entries  
  123.                 Double d2 = Double.valueOf( stack.pop() );  
  124.                 Double d1 = Double.valueOf( stack.pop() );  
  125.                  
  126.                 //Get the result  
  127.                 Double result = token.compareTo("+") == 0 ? d1 + d2 :  
  128.                                 token.compareTo("-") == 0 ? d1 - d2 :  
  129.                                 token.compareTo("*") == 0 ? d1 * d2 :  
  130.                                                             d1 / d2;                
  131.                                  
  132.                 // Push result onto stack  
  133.                 stack.push( String.valueOf( result ));                                                  
  134.             }                          
  135.         }          
  136.          
  137.         return Double.valueOf(stack.pop());  
  138.     }  
  139.    
  140.     public static void main(String[] args) {  
  141.         String[] input = "( 1 + 2 ) * ( 3 / 4 ) - ( 5 + 6 )".split(" ");        
  142.         String[] output = infixToRPN(input);  
  143.          
  144.         // Build output RPN string minus the commas  
  145.          for (String token : output) {  
  146.             System.out.print(token + " ");  
  147.         }  
  148.          
  149.         // Feed the RPN string to RPNtoDouble to give result  
  150.         Double result = RPNtoDouble( output );                        
  151.     }  
  152. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement