Add Read & infix to prefix algo

This commit is contained in:
2017-03-07 12:57:49 +01:00
parent bd989a67c1
commit b75156a4d4
2 changed files with 118 additions and 0 deletions

109
src/Expression.java Normal file
View File

@@ -0,0 +1,109 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
/**
* Created by xawirses on 28/02/17.
*/
public class Expression {
private String expression;
public Expression(){
readExpression();
parse();
}
public void readExpression(){
try {
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
expression = buff.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
private String reverseExpression(String exp) {
String reverse = "";
for (int i = exp.length()-1; i >= 0; i--) {
char c = exp.charAt(i);
switch (c) {
case '(':
reverse += ")";
break;
case ')':
reverse += "(";
break;
default:
reverse += c;
}
}
return reverse;
}
private boolean isParenthesis(char c) {
return c == '(' || c == ')';
}
private boolean isOperator(char c) {
for (int i = 0; i < Operator.nbOperators; i++) {
if(Operator.operators[i] == c)
return true;
}
return false;
}
private boolean isHighterOperator(char current, char stack) {
int pCurrent = 0;
int pStack = 0;
for (int i = 0; i < Operator.nbOperators; i++) {
if(Operator.operators[i] == current)
pCurrent = i;
if(Operator.operators[i] == stack)
pStack = i;
}
return (pCurrent >= pStack);
}
private void parse() {
String reverse = reverseExpression(expression);
String reversePrefix = "";
LinkedList<String> stack = new LinkedList<String>();
for (int i = 0; i < reverse.length(); i++) {
char c = reverse.charAt(i);
if (!isOperator(c)) {
reversePrefix += c;
} else if(c == '(') {
stack.addLast(String.valueOf(c));
} else if(isOperator(c) && !isParenthesis(c)) {
while (!stack.isEmpty() && !isParenthesis(stack.peekLast().charAt(0)) && isHighterOperator(c, stack.peekLast().charAt(0))) {
reversePrefix += stack.pollLast();
}
stack.addLast(String.valueOf(c));
} else if(c == ')') {
while (!stack.peekLast().equals("(")) {
System.out.println(reversePrefix);
System.out.println(stack.peekLast());
reversePrefix += stack.pollLast();
}
stack.pollLast();
} else {
System.err.println("WTF !!");
}
}
while (!stack.isEmpty())
reversePrefix += stack.pollLast();
System.out.println(reverseExpression(reversePrefix));
}
public static void main(String[] args) {
Expression e = new Expression();
}
}

9
src/Operator.java Normal file
View File

@@ -0,0 +1,9 @@
/**
* Created by xawirses on 28/02/17.
*/
public class Operator {
public static final int nbOperators = 9;
public static final char operators[] = {'!', 'L', 'M', '(', ')', '&', '|', '>', '='};
}