On my way to sucess

Sunday, January 8, 2012

Infix to Postfix

Evaluating a 2*(3+4) expression would be difficult if it's not converted in to postfix. When converted to postfix this expression would be 234+*. Here are some more examples.
(1+2)*(4-3)  =  12+43-*
((1+2)*3)-4  =  12+3*4-
1*2+3*4      =   12*34*+

When these expressions are evaluated the operators must be stored in a stack.
All the operators are and brackets are stored in a stack. The following example shows how stack stores operators.

1+2*(4-3)

Stack contents
       +
       +
       +*
       +*(
       +*(
       +*(-
       +*(-
       +*(
       +*(
       +*
       +

The following it shows the java code for evaluating and expression after converted to postfix.



public abstract class ArithmeticExpression{

public abstract double evaluate(double x, double y);

public abstract void display(double x, double y, double ans);

}



class Addition extends ArithmeticExpression {
double ans =0.0;
double x;
double y;

public double evaluate (double x, double y)
{


ans = x + y;
display(x, y, ans);
return ans;




}


public void display(double x, double y, double ans)
{

System.out.println(x + " + " + y + " = " + ans);
}

}


public class Subtraction extends ArithmeticExpression{

double ans =0.0;
double x;
double y;

public double evaluate (double x, double y)
{


ans = x - y;
display(x, y, ans);
return ans;




}


public void display(double x, double y, double ans)
{

System.out.println(x + " - " + y + " = " + ans);
}
}


public class Division extends ArithmeticExpression{

double ans =0.0;
double x;
double y;
public double evaluate(double x, double y){
ans = x/y;




ans = x + y;
display(x, y, ans);
return ans;




}



public void display(double x, double y, double ans)
{

System.out.println(x + " / " + y + " = " + ans);
}

}



class Multiplication {
double ans =0.0;
double x;
double y;

public double evaluate (double x, double y)
{

ans=x*y;
return ans;
}

public void display(double x, double y, double ans)
{

System.out.println(x + " * " + y + " = " + ans);
}

}

import java.util.Stack;

public class bodmas {
Addition add = new Addition();
Subtraction sub = new Subtraction();
Multiplication mul = new Multiplication();
Division div = new Division();
public String toPostfix(String str){
   String[] Infix = str.split(",");
    
   
   Stack<String> stack = new Stack<String>();
   StringBuilder Postfix = new StringBuilder();

  for (int i = 0; i <Infix.length ; i++){
 
  if (findDouble(Infix[i]))
  Postfix.append(Infix[i]+",");
   
  else if (Infix[i].equals("."))         
    stack.push(Infix[i]);     
 
  else if (Infix[i].equals("("))
  stack.push(Infix[i]);
   
  else if ((Infix[i].equals("*")) || (Infix[i].equals("+")) || (Infix[i].equals("-")) || (Infix[i].equals("/"))){
         
    while ((stack.size() > 0) && (!stack.peek().equals("("))){
   
    if (orderCheck(stack.peek(), Infix[i]))                 
    Postfix.append(stack.pop() + ",");
   
  else
  break;
    }
    stack.push(Infix[i]);
    }
    else if (Infix[i].equals(")")){
    while ((stack.size() > 0) && (!stack.peek().equals("("))){
    Postfix.append(stack.pop() + ",");
    }
 
  if (stack.size() > 0)
  stack.pop(); 
  }
    }
   
   while (stack.size() > 0){
    Postfix.append(stack.pop() + ",");
   }
   
   String finalResults = " ";
   
   if (Postfix.toString().endsWith(",")){
    finalResults = Postfix.toString();
    finalResults = finalResults.substring(0, finalResults.lastIndexOf(','));
   }
   return finalResults;
}
public double calculate(String str){
String[] arrStr = str.split(",");
Stack<String> stackStr = new Stack<String>();

for (int i = 0; i < arrStr.length; i++)
{
if (findDouble(arrStr[i]))
{
stackStr.push(arrStr[i]);
}
else
{
String str1 = stackStr.pop();
String str2 = stackStr.pop();
             
double tempAnswer = calculation(str2, str1, arrStr[i]);
stackStr.push(Double.toString(tempAnswer));
}
}

return Double.parseDouble(stackStr.pop());
}
public double calculation(String num1, String num2, String oper){
        double answer = 0;
        double x = Double.parseDouble(num1);
        double y = Double.parseDouble(num2);
        
        if (oper.equals("+")){
       
        answer = add.evaluate(x, y);   
        }
        
        else if (oper.equals("-")){
       
        answer = sub.evaluate(x,y); 
        }
        
        else if (oper.equals("*")){
       
        answer = mul.evaluate(x,y); 
        }
        
        else if (oper.equals("/")){
       
        answer = div.evaluate(x,y); 
        }
        
        return answer;
    }
private boolean orderCheck(String oper1,String oper2){
      
if (oper1.equals("*") && oper2.equals("-")) 
   return true;
 
if (oper1.equals("+") && oper2.equals("-")) 
   return true;
if (oper1.equals("+") && oper2.equals("*")) 
return false;
 
if (oper1.equals("-") && oper2.equals("*")) 
   return false;
 
return true;
}
public boolean findDouble(String chk){ 
try{
Double.parseDouble(chk);
return true;
}
catch(NumberFormatException e){
return false;
}
public boolean validate(String exprevalid){
int open = 0;
int close = 0;
for(int i=0; i<exprevalid.length(); i++){
if(exprevalid.charAt(i) == '('){
open++;
}
else if(exprevalid.charAt(i) == ')'){
close++;
}
}
if(open != close){
return false;
}
else{
return true;
}
}
}

import java.util.Scanner;

public class CalculatorTest  {
public static void main(String[] args){
Scanner i1 = new Scanner(System.in);
RandomCalculation random1 = new RandomCalculation();
bodmas bod = new bodmas();
System.out.println("What do you want to do");
System.out.println("[1] Calculation");
System.out.println("[2] Random");
System.out.println("[3] Exit");
System.out.println();
System.out.println("Enter 1 or 2 or 3");
int selection = 0;
try{
selection = i1.nextInt();
}
catch(Exception e){
System.out.println();
System.out.println("Wrong Input");
System.out.println();
System.exit(0);
}
System.out.println();
if(selection == 1 || selection == 2){
String expre = " ";
if(selection == 1)
{
System.out.print("Enter the Expression: ");
expre =i1.next();
}
else if(selection == 2){
System.out.println();
System.out.println("Random Calculation");
System.out.println();
expre = random1.randomExpression();
System.out.println(expre);
System.out.println();
}
if(bod.validate(expre)){
String infixExpre="";
for (int i = 0; i < expre.length();i++){
if (expre.charAt(i)== '+')
{
infixExpre = infixExpre + ",+,";
}
else if (expre.charAt(i)== '-')
{
infixExpre = infixExpre+ ",-,";
}
else if (expre.charAt(i)== '*')
{
infixExpre = infixExpre + ",*,";
}
else if (expre.charAt(i)== '/')
{
infixExpre= infixExpre + ",/,";
}
else if (expre.charAt(i)== '(')
{
if(i==0)
{
infixExpre = infixExpre + "(,";
}
else
{
infixExpre = infixExpre+ ",(,";
}
}
else if (expre.charAt(i)== ')')
{
if(i==0)
{
infixExpre = infixExpre + "),";
}
else
{
infixExpre = infixExpre + ",),";
}
}
else
{
infixExpre = infixExpre + expre.charAt(i);
}
}
try{
String postFixExpre = bod.toPostfix(infixExpre);
bod.calculate(postFixExpre);
}
catch(Exception ex){
System.out.println("Invalid expression entered!!!");
}
}
else{
System.out.println("Invalid expression entered!!!");
}
System.out.println();
}
else{
System.out.println("Invalid selection!!!");
System.out.println();
}
}
}

This also includes the code to create random expressions and calculate the answer of them

import java.util.Random;

public class RandomCalculation {

public String randomExpression(){

Random random = new Random();
String expre = " ";
int brackets = random.nextInt(6);
int signs=2*brackets-1;
char [] finalSigns=new char [signs];
int [] signs1=new int[signs];
int [] values= new int[2*brackets];
for(int i = 0; i < 2*brackets; i++){
values[i] = random.nextInt(50);
}
for(int j = 0; j < signs; j++){
signs1[j] = random.nextInt(4);
}
for(int k = 0; k < signs; k++){
if(signs1[k] == 0){
finalSigns[k] = '+';
}
if(signs1[k] == 1){
finalSigns[k] = '-';
}
if(signs1[k] == 2){
finalSigns[k] = '*';
}
if(signs1[k] == 3){
finalSigns[k] = '/';
}
}
for(int i = 0; i < brackets; i++){
expre += '(';
expre += Integer.toString(values[i]);
expre += finalSigns[i];
expre += Integer.toString(values[i+1]);
expre += ')';
if(i != brackets-1){
expre += finalSigns[1+i];
}
}
return expre;
}
}


This was the code which I did for my Object Oriented Programming coursework.