-
-
Save taylorsmithgg/d2e320681d7fa68fe610da02d2ad6206 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
import java.util.stream.Collectors; | |
public class Infix { | |
public static String infixToPostfix(String infixexpr) { | |
HashMap<String, Integer> prec = new HashMap<>(); | |
prec.put("*", 3); | |
prec.put("/", 3); | |
prec.put("+", 2); | |
prec.put("-", 2); | |
prec.put("(", 1); | |
Stack opStack = new Stack(); | |
List postfixList = new ArrayList<>(); | |
String[] tokenList = infixexpr.split(" "); | |
// Arrays.stream(tokenList).collect(Collectors.toList()).forEach(System.out::println); | |
for(String token : tokenList){ | |
if(!token.isEmpty()) { | |
if (Character.isAlphabetic(token.charAt(0)) || Character.isDigit(token.charAt(0))) { | |
postfixList.add(token); | |
} else if (Objects.equals(token, "(")) { | |
opStack.push(token); | |
} else if (Objects.equals(token, ")")) { | |
String topToken = (String) opStack.pop(); | |
while (topToken.equals("(")) { | |
postfixList.add(topToken); | |
topToken = (String) opStack.pop(); | |
} | |
} else { | |
if (!opStack.empty()) { | |
while (prec.get(opStack.peek()) >= prec.get(token)) { | |
postfixList.add(opStack.pop()); | |
} | |
} | |
opStack.push(token); | |
} | |
} | |
} | |
while(!opStack.isEmpty()) { | |
String token = (String) opStack.pop(); | |
postfixList.add(token); | |
} | |
return (String) postfixList.stream().map(Object::toString).collect(Collectors.joining("")); | |
} | |
public static int evaluatePostfix(String expression) { | |
String[] nextItem = expression.split(" "); | |
Stack<Integer> operands = new Stack<>(); | |
for(String item : nextItem) { | |
if(!item.isEmpty()) { | |
if (Character.isDigit(item.charAt(0))) { | |
operands.push(Integer.parseInt(item)); | |
} else { | |
double operand2 = operands.pop(); | |
double operand1 = operands.pop(); | |
double result = applyOperator(item.charAt(0), operand1, operand2); | |
operands.push((int) result); | |
} | |
} | |
} | |
return operands.pop(); | |
} | |
public static double applyOperator(Character c, double first, double second) { | |
if (Objects.equals(c, '+')) { | |
return first + second; | |
} else if (c == '-') { | |
return first - second; | |
} else if (Objects.equals(c, '*')) { | |
return first * second; | |
} else if(Objects.equals(c, '/')) { | |
if(second == 0) | |
throw new UnsupportedOperationException("Cant divide by 0"); | |
return first / second; | |
} else if(Objects.equals(c, '^')) { | |
return Math.pow(first, second); | |
} else { | |
throw new UnsupportedOperationException("Invalid Operator"); | |
} | |
} | |
public static boolean hasPrecedence(char op1, char op2) | |
{ | |
if (op2 == '(' || op2 == ')') | |
return false; | |
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) | |
return false; | |
else | |
return true; | |
} | |
public static double evaluateInfix(String expression) { | |
char[] tokens = expression.toCharArray(); | |
// Stack for numbers: 'values' | |
Stack<Double> values = new Stack<>(); | |
// Stack for Operators: 'ops' | |
Stack<Character> ops = new Stack<>(); | |
for (int i = 0; i < tokens.length; i++) | |
{ | |
// Current token is a whitespace, skip it | |
if (tokens[i] == ' ') | |
continue; | |
// Current token is a number, push it to stack for numbers | |
if (tokens[i] >= '0' && tokens[i] <= '9') | |
{ | |
StringBuffer sbuf = new StringBuffer(); | |
// There may be more than one digits in number | |
while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9') | |
sbuf.append(tokens[i++]); | |
values.push(Double.parseDouble(sbuf.toString())); | |
} | |
// Current token is an opening brace, push it to 'ops' | |
else if (tokens[i] == '(') | |
ops.push(tokens[i]); | |
// Closing brace encountered, solve entire brace | |
else if (tokens[i] == ')') | |
{ | |
while (ops.peek() != '(') | |
values.push(applyOperator(ops.pop(), values.pop(), values.pop())); | |
ops.pop(); | |
} | |
// Current token is an operator. | |
else if (tokens[i] == '+' || tokens[i] == '-' || | |
tokens[i] == '*' || tokens[i] == '/') | |
{ | |
// While top of 'ops' has same or greater precedence to current | |
// token, which is an operator. Apply operator on top of 'ops' | |
// to top two elements in values stack | |
while (!ops.empty() && hasPrecedence(tokens[i], ops.peek())) | |
values.push(applyOperator(ops.pop(), values.pop(), values.pop())); | |
// Push current token to 'ops'. | |
ops.push(tokens[i]); | |
} | |
} | |
// Entire expression has been parsed at this point, apply remaining | |
// ops to remaining values | |
while (!ops.empty()) | |
values.push(applyOperator(ops.pop(), values.pop(), values.pop())); | |
// Top of 'values' contains result, return it | |
return values.pop(); | |
} | |
public static void main(String[] args) { | |
Scanner input = new Scanner(System.in); | |
System.out.println("Please enter a expression: "); | |
String userInput = input.nextLine(); | |
String postfix = infixToPostfix(userInput); | |
System.out.println("Postfix: " + postfix); | |
System.out.println("Postfix result: " + evaluatePostfix(postfix)); | |
System.out.println("Infix result: " + evaluateInfix(userInput)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment