Last active
March 11, 2016 13:41
-
-
Save humayun0156/7b5d800d341f30541f3b to your computer and use it in GitHub Desktop.
Shunting-yard algorithm
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.HashMap; | |
import java.util.Map; | |
import java.util.Stack; | |
/** | |
* @author humayun | |
* | |
* https://en.wikipedia.org/wiki/Shunting-yard_algorithm | |
* | |
*/ | |
public class ShuntingYardAlgorithm { | |
public static void main(String[] args) { | |
String infix = "3+4*2/(1-5)"; | |
String output = new ShuntingYardAlgorithm().shuntingYard(infix); | |
System.out.println(output); | |
} | |
private enum Operator { | |
ADD(1), SUBTRACT(2), MULTIPLY(3), DIVIDE(4); | |
final int precedence; | |
Operator(int p) { | |
precedence = p; | |
} | |
} | |
private Map<String, Operator> operatorMap = new HashMap<String, Operator>() {{ | |
put("+", Operator.ADD); | |
put("-", Operator.SUBTRACT); | |
put("*", Operator.MULTIPLY); | |
put("/", Operator.DIVIDE); | |
}}; | |
private boolean isHigherPrec(String op, String sub) { | |
return (operatorMap.containsKey(sub) && | |
operatorMap.get(sub).precedence >= operatorMap.get(op).precedence); | |
} | |
public String shuntingYard(String infix) { | |
StringBuilder output = new StringBuilder(); | |
Stack<String> stack = new Stack<String>(); | |
for (String token : infix.split("")) { | |
//operator | |
if (operatorMap.containsKey(token)) { | |
while ( ! stack.isEmpty() && isHigherPrec(token, stack.peek())) { | |
output.append(stack.pop()).append(' '); | |
} | |
stack.push(token); | |
} | |
//left parenthesis | |
else if (token.equals("(")) { | |
stack.push(token); | |
} | |
//right parenthesis | |
else if (token.equals(")")) { | |
while ( ! stack.peek().equals("(")) { | |
output.append(stack.pop()).append(' '); | |
} | |
stack.pop(); | |
} | |
//digit | |
else { | |
output.append(token).append(' '); | |
} | |
} | |
while ( ! stack.isEmpty()) { | |
output.append(stack.pop()).append(' '); | |
} | |
return output.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment