Created
December 21, 2022 13:26
-
-
Save ravichandrae/3387c18ddf57564c0288509c614e82fe to your computer and use it in GitHub Desktop.
Given an expression like add( sub(3, 2), add(0, 1) ), evaluate their results.
This file contains 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.Stack; | |
public class ExpressionEvaluation { | |
public static void main(String[] args) { | |
String expression = "add( 1, 2)"; | |
int result = evaluateExpression(expression); | |
System.out.println(result); | |
expression = "add(sub(2, 1), 3)"; | |
System.out.println(evaluateExpression(expression)); | |
expression = "add(3, sub(22, 20))"; | |
System.out.println(evaluateExpression(expression)); | |
expression = "sub( add(18, 20), sub(22, 20))"; | |
System.out.println(evaluateExpression(expression)); | |
expression = "sub( add(add(10,8), 20), sub(22, 20))"; | |
System.out.println(evaluateExpression(expression)); | |
expression = "add( abc, 2)"; | |
System.out.println(evaluateExpression(expression)); | |
expression = "add(-10, sub(22, 20))"; | |
System.out.println(evaluateExpression(expression)); | |
expression = "add(-10, sub(2+2, 20))"; | |
System.out.println(evaluateExpression(expression)); | |
} | |
private static int evaluateExpression(String expression) { | |
char[] expChars = expression.toCharArray(); | |
String token = ""; | |
Stack<String> stack = new Stack<>(); | |
for (int i = 0; i < expChars.length; i++) { | |
char ch = expChars[i]; | |
if (Character.isAlphabetic(ch) || Character.isDigit(ch) || ch == '-' || ch == '+') { | |
token += ch; | |
} else { | |
if (Character.isSpaceChar(ch) || ch == '(' || ch == ')' || ch == ',') { | |
if (!token.isEmpty()) { | |
stack.push(token); | |
} | |
token = ""; | |
} | |
if (ch == ')') { | |
//Get operation and operands | |
int op1 = 0, op2 = 0; | |
String operand = ""; | |
try{ | |
operand = stack.pop(); | |
op2 = Integer.parseInt(operand); | |
operand = stack.pop(); | |
op1 = Integer.parseInt(operand); | |
} catch (NumberFormatException nfe) { | |
System.out.println("Bad input " + operand + " at " + expression.indexOf(operand)); | |
return -1; | |
} | |
String operation = stack.pop(); | |
stack.push(Integer.toString(getResult(operation, op1, op2))); | |
} | |
} | |
} | |
return Integer.parseInt(stack.pop()); | |
} | |
private static int getResult(String operation, int op1, int op2) { | |
int result = 0; | |
if (operation.equals("add")) { | |
result = op1 + op2; | |
} else if (operation.equals("sub")) { | |
result = op1 - op2; | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment