miki
BAN USER
Tried to solve it with a complex logic and it kind of worked but there were too many raise conditions and the code wasn't readable at all.
Using the Dijkstra 2 stack algorithm it is pretty elegant.
public class EvaluateMathematicalExpression {
Map<Character, Integer> variables;
public EvaluateMathematicalExpression(Map<Character, Integer> variables) {
this.variables = variables;
}
public static void main(String[] args){
Map<Character, Integer> variables = new HashMap<>();
List<String> expressions = new ArrayList<>();
Scanner scan = new Scanner(System.in);
System.out.println("enter number of variables:");
int variablesNumber = scan.nextInt();
scan.nextLine();
System.out.println("now the variables: ");
for(int i = 0; i<variablesNumber;i++){
String line = scan.nextLine();
String[] varVal = line.split("=");
variables.put(varVal[0].charAt(0),Integer.valueOf(varVal[1]));
}
System.out.println("--------------");
System.out.println("enter number of expressions:");
int expressionsNumber = scan.nextInt();
scan.nextLine();
System.out.println("and the expressions: ");
for(int i = 0; i<expressionsNumber;i++) {
expressions.add(scan.nextLine());
}
EvaluateMathematicalExpression eme = new EvaluateMathematicalExpression(variables);
for(String line : expressions){
try{
System.out.println("Evaluation of " + line + ": " + eme.evaluateDijkstra(line));
} catch (Exception e){
System.out.println("Compile error for " + line);
}
}
}
public int evaluateDijkstra(String expression){
char[] chars = expression.toCharArray();
Stack<Integer> vals = new Stack<>();
Stack<Character> ops = new Stack<>();
for(int i = 0; i<chars.length;i++){
char currCh = chars[i];
if(currCh == ' ') continue;
if(isSign(currCh)){
if(!ops.empty() && shouldCalcPrev(currCh, ops.peek())){
while(!ops.empty() && ops.peek() != null) {
char sign = ops.pop();
int right = vals.pop();
int left = vals.pop();
vals.push(calc(left, right, sign));
}
ops.push(currCh);
} else {
ops.push(currCh);
}
} else {
Integer val = variables.get(currCh);
if(val == null){
throw new IllegalArgumentException("Unexpected character " + currCh);
}
vals.push(val);
}
}
while(!ops.empty()){
char sign = ops.pop();
int right = vals.pop();
int left = vals.pop();
vals.push(calc(left,right,sign));
}
return vals.pop();
}
public int calc(int left, int right, char ch){
if(ch == '+'){
return left + right;
} else if(ch == '-'){
return left - right;
} else if(ch == '*'){
return left * right;
} else if(ch == '/'){
return left / right;
} else {
throw new IllegalArgumentException("Compilation error, sign expected");
}
}
/**
* "*" and "/" get higher priority, if we reached to "+" and "-", we can(and should) calculate previous operations.
* @param sign
* @param prevSign
* @return
*/
public boolean shouldCalcPrev(char sign, Character prevSign){
if(prevSign == null){
return false;
}
if( (sign == '+' || sign == '-') && (prevSign == '*' || prevSign == '/')) return true;
return false;
}
public boolean isSign(char ch){
if(ch == '-' || ch == '+' || ch == '*' || ch == '/') return true;
return false;
}
}
Repsharonpkarr, None at BT
Hi! My name is Mary. I am a writer for a variety of web and multi-platform applications.I am a ...
Repewasam940, Backend Developer at Absolute Softech Ltd
I am a 29-year-old Investment Advisor from New York. I help people make the right investment decision. I met many ...
Repannasteven1246, Analyst at Accenture
Creative, highly visual fashion professional who can brilliantly mix and match the technical expertise and intuition like fabric and color ...
Repsylviarashtons, Accountant at ASAPInfosystemsPvtLtd
I am a journalist. Outside the office, I enjoy additional writing time in a different genre of historical fiction. I ...
Repsherrymrex, Computer Scientist at CGI-AMS
I am Sherry from West Palm Beach USA, I started my journey in 2016 as a yoga teacher. I like ...
Repamandaben422, Graphics Programmer at Abs india pvt. ltd.
Hi, I am a webmaster from the USA. I think social networks have the power to connect two different people ...
RepLizzieGibson, Cloud Support Associate at Aspire Systems
I'm an engineering student from Huntsville, AL USA. Have more interest in management and stuff related to business. Promptly ...
Repthubmorfin, Android Engineer at ABC TECH SUPPORT
I am currently working as a safety-focused Service Technician from Red Bank. I execute routine maintenance work while advising clients ...
RepI am Susan From Wasilla USA. and my strong interest in yoga and reading historical books. I have a large ...
Rephoychrista, Blockchain Developer at ASU
Worked with Clients to guide them through the event details about copier leasing companies and served as their personal coordinator ...
RepShirleyCWest, Software Engineer at Agilent Technologies
Hello, me Shirley and I from Savage. I am an artist and I love to doing art and I am ...
- miki November 01, 2018