Sunday, 14 February 2016

Java Program Reads an Infix Expression, Converts the Expression to Postfix form and then Evaluates the Postfix Expression

import java.util.Scanner;

class CharacterStack {

    int size, top;
    char stack[];
   
    CharacterStack (int num) {
        size = num;
        top = -1;
        stack = new char[num];
    }
   
    public void push(char n) {
        stack[++top] = n;
    }
   
    public char pop() {
        return stack[top--];
    }
   
    public char peek() {
        return stack[top];
    }
   
    public boolean isEmpty() {
        return top == -1;
    }
   
    public boolean isFull() {
        return top == size;
    }
}

public class InfixToPostfix {  
   
    public static String infixToPostfix(String infix) {
       
        char symbol;
        String postfix = "";
        CharacterStack operator = new CharacterStack(infix.length());
       
        for(int i=0; i < infix.length(); ++i) {
           
            symbol = infix.charAt(i);
           
            if(Character.isLetter(symbol))
                postfix += symbol;
           
            else if( symbol ==  '(' || symbol == '{' || symbol == '[' )
                operator.push(symbol);
           
            else if( symbol ==  ')' || symbol == '}' || symbol == ']' ) {
                while( !( operator.peek() == '(' ||operator.peek() == '{' ||operator.peek() == '[') )
                    postfix += operator.pop();
                operator.pop();
            } else {
                while(!operator.isEmpty() && !(operator.peek()=='(') && isPref(symbol) <= isPref(operator.peek()))
                    postfix += operator.pop();
                operator.push(symbol);
            }
        }
        while(!operator.isEmpty())
            postfix += operator.pop();
        return postfix;
    }
   
    private static int isPref(char c) {
        if(c == '+' || c == '-') 
            return 1;
        if(c == '*' || c == '/' || c == '%')
            return 2;
        if(c == '^')
            return 3;
        return 0;
    }
   
    private static int postfixEvaluation(String infixToPostfix) {
        String alphabet = "abcdefghijklmnopqrstuvwxyz";
        int[] counts = new int[26];
        Scanner input = new Scanner(System.in);
       
          for(int i=0; i < infixToPostfix.length(); i++) {
              char ch = Character.toLowerCase(infixToPostfix.charAt(i));
              int index = alphabet.indexOf(ch);
              if(index != -1)
                   counts[index] += 1;
        }
       
        for(int i=0; i<26; i++) {
            if(counts[i] > 0) {
                System.out.print(" Enter value of " + alphabet.charAt(i) + " : ");
                counts[i] = input.nextInt();
            }  
        }
       
        CharacterStack token = new CharacterStack(infixToPostfix.length());
       
        for(int i=0; i < infixToPostfix.length(); i++) {           
            char c = infixToPostfix.charAt(i);
           
            if(Character.isLetter(c)) {               
                int index = alphabet.indexOf(c);
                token.push((char)counts[index]);
            }
            else {
                int x = token.pop();
                int y = token.pop();
                int calculation = calculation(y, x, c);
                token.push((char)calculation);
            }
        }
        return (int)token.pop();
    }
   
    private static int calculation(int a, int b, char c) {
        switch(c) {
            case '+' : return a+b;
            case '-' : return a-b;
            case '*' : return a*b;
            case '/' : return a/b;
            case '%' : return a%b;
            case '^' : return (int) Math.pow(a, b);
        }
        return 1;
    }
   
    public static void main(String[] ar) {
       
        Scanner input = new Scanner(System.in);
       
        System.out.print(" Enter Infix expression : ");
        String str = input.nextLine();
       
        String infixToPostfix = infixToPostfix(str);
        System.out.println(" Postfix Expression : " + infixToPostfix);
       
        int postfixEvaluation = postfixEvaluation(infixToPostfix);
        System.out.println("\n Evaluation of Postfix: " + postfixEvaluation);
    }
}

No comments:

Post a Comment