Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- import java.util.Stack;
- public class PolishExpression {
- private final static Map<String, Integer> relativePriorities = Map.of
- ("+", 1, "-", 1, "*", 3, "/", 3, "^", 6, "operand", 7, "(", 9, ")", 0);
- private final static Map<String, Integer> stackPriorities = Map.of
- ("+", 2, "-", 2, "*", 4, "/", 4, "^", 5, "operand", 8, "(", 0);
- private final String expression;
- private final int rank;
- private PolishExpression(String expression) {
- this.expression = expression;
- this.rank = countRank(expression);
- }
- public int getRank() {
- return rank;
- }
- @Override
- public String toString() {
- return expression;
- }
- public static PolishExpression getInstance(String expression) {
- System.out.println("SYMBOL STACK RESULT");
- List<String> symbols = getSymbols(expression);
- Stack<String> stack = new Stack<>();
- StringBuilder res = new StringBuilder();
- for (String symbol : symbols) {
- boolean deeper = true;
- int relativePriority = getPriority(symbol, relativePriorities);
- printState(symbol, stack, res.toString());
- if (!stack.isEmpty()) {
- while (deeper) {
- String stackSymbol = stack.peek();
- int stackPriority = getPriority(stackSymbol, stackPriorities);
- if (stackSymbol.equals("(") && symbol.equals(")")) {
- stack.pop();
- break;
- }
- if (relativePriority > stackPriority) {
- stack.push(symbol);
- deeper = false;
- } else {
- res.append(stack.pop());
- deeper = true;
- }
- if (stack.isEmpty()) {
- stack.push(symbol);
- deeper = false;
- }
- }
- } else {
- stack.push(symbol);
- }
- }
- while (!stack.isEmpty()) {
- res.append(stack.pop());
- }
- return new PolishExpression(res.toString());
- }
- private static void printState(String symbol, Stack<String> stack, String res) {
- String stackStr = stack.toString().replaceAll("\\s|,|\\[|\\]", "");
- System.out.printf("%2s", symbol);
- System.out.printf("%15s", stackStr);
- System.out.printf("%20s", res);
- System.out.println();
- }
- private int countRank(String expression) {
- List<String> symbols = getSymbols(expression);
- int rank = 0;
- for (String symbol : symbols) {
- if (symbol.matches("^\\w$")) {
- rank += 1;
- } else {
- rank -= 1;
- }
- }
- return rank;
- }
- private static List<String> getSymbols(String expression) {
- List<String> symbols = new ArrayList<>();
- for (int i = 0; i < expression.length(); i++) {
- symbols.add(String.valueOf(expression.charAt(i)));
- }
- return symbols;
- }
- private static int getPriority(String symbol, Map<String, Integer> priorities) {
- if (symbol.matches("^\\w$")) {
- return priorities.get("operand");
- } else {
- return priorities.get(symbol);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement