Evaluating Expression in java - java

I am getting output impossible.
but it must be possible.
when i check at the editor it shows that that the case is always true
i.e last three cases of switch.
public String isPossible(String express) {
char a = ' ';
char b = ' ';
boolean flag = true;
Stack<Character> pile = new Stack<Character>();
char [] array = express.toCharArray();
for (int i = 0 ; i < array.length ; i++) {
a = array[i];
switch (a) {
case '(':
pile.push(a);
break;
case '{':
pile.push(a);
break;
case '[':
pile.push(a);
break;
case ')':
b = pile.pop();
if (b != '(' || b != 'X')
flag = false;
break;
case '}':
b = pile.pop();
if (b != '{' || b != 'X')
flag = false;
break;
case ']':
b = pile.pop();
if (b != ']' || b != 'X')
flag = false;
break;
}
}
if (flag == false || pile.size() % 2 != 0)
return "impossible";
else
return "possible";
}
public static void main(String args[]) {
Merge a = new Merge();
System.out.println(a.isPossible("(())"));
}

Your logic is incorrectly using the || (or) operator. It is always true that b is not '(' or it's not 'X'. You want && (and).
Replace
if(b!='(' || b!= 'X')
with
if(b!='(' && b!= 'X')
and similarly for the other if conditions in the case statements.

Related

Recursive method to evaluate expressions just work when method is called once

I'm writing a code to valuate math expressions. The code just works when I call the methode once. But I have more than one expression to evaluate and it just break when I call the method more than two times. I get the following error:
-2
Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Stack.java:102)
at java.util.Stack.pop(Stack.java:84)
at Evaluate.parse(Evaluate.java:58)
at Evaluate.main(Evaluate.java:11)
I see that the code gives me the expected result (the -2) but what I'm doing wrong regarding the methode that gives me this error
My code:
public class Evaluate {
static Stack<Character> ops = new Stack<Character>();
static Stack<Integer> vals = new Stack<Integer>();
static int i = 0;
public static void main(String[] args) {
System.out.println(parse("(4-(7-1))"));
System.out.println(parse("8"));
System.out.println(parse("((1+1)*(2*2))"));
System.out.print("\n");
System.out.println(parse("(6/(3/2))"));
}
private static int parse(String expression) {
char[] tokens = expression.toCharArray();
while (tokens.length > i) {
char s = tokens[i];
if (s == '(') {
ops.push(tokens[i]);
} else if (s == '+' || s == '-' || s == '*' || s == '/') {
while (!ops.empty() && hasPrecedence(tokens[i], ops.peek()))
vals.push(applyOp(ops.pop(), vals.pop(), vals.pop()));
ops.push(s);
} else if (s == ')') {
char op = ops.pop();
int v = vals.pop();
while (ops.peek() != '(')
vals.push(applyOp(ops.pop(), vals.pop(), vals.pop()));
ops.pop();
if (op == '+') {
v = vals.pop() + v;
} else if (op == '-') {
v = vals.pop() - v;
} else if (op == '*') {
v = vals.pop() * v;
} else if (op == '/') {
v = vals.pop() / v;
}
vals.push(v);
} else {
vals.push(Character.getNumericValue(s));
}
i++;
}
while (!ops.empty())
vals.push(applyOp(ops.pop(), vals.pop(), vals.pop()));
return vals.pop();
}
public static boolean hasPrecedence(char op1, char op2) {
if (op2 == '(' || op2 == ')')
return false;
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return false;
else
return true;
}
// A utility method to apply an
// operator 'op' on operands 'a'
// and 'b'. Return the result.
public static int applyOp(char op, int b, int a) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
throw new UnsupportedOperationException("Cannot divide by zero");
return a / b;
}
return 0;
}

Fails for the testcase "([}}])" to validate expression(balancing parenthesis problem) which is coded in java

This code is written when I was trying to solve the problem on Leet code(the link to the problem is given below), which performs the balancing parenthesis but failing for the condition ([}}]) could anyone help me.
Thank you.
problem link---> https://leetcode.com/problems/valid-parentheses/
import java.util.*;
public class expressionValidation
{
public static void main(String[] args)
{
try (Scanner sc = new Scanner(System.in))/*trying to avoid any kind of exceptions*/
{
String str = sc.nextLine();
String exp = "";/*new string to modify the given expression*/
int l = str.length();
for(int i=0;i<l;i++)
{
if(str.charAt(i)=='{'||str.charAt(i)=='('||str.charAt(i)=='['||str.charAt(i)=='}'||str.charAt(i)==']'||str.charAt(i)==')')
{
exp+=str.substring(i,i+1);/*newly modified string afterstrong text removing everything except brackets'(' '[' '{' ' }' ']' ')'*/
}
}
stack ob = new stack();
System.out.println(ob.isValid(exp)?"Balanced":"NOT Balanced");
}
}
}
## The following is the stack class
class stack
{
boolean isValid(String exp)
{
int l =exp.length();
if(l%2!=0)
return false;
Stack<Character> st = new Stack<Character>();
for(int i=0;i<l;i++)
{
if(exp.charAt(i)=='{' ||exp.charAt(i)=='(' ||exp.charAt(i)=='[' ) {
st.push(exp.charAt(i));
}
else if(exp.charAt(i)=='}' && !(st.isEmpty()) && st.peek()=='{') {
st.pop();
}
else if(exp.charAt(i)==')' && !(st.isEmpty()) && st.peek()=='(') {
st.pop();
}
else if(exp.charAt(i)==']' && !(st.isEmpty()) && st.peek()=='[') {
st.pop();
}
String str = st.toString();
System.out.println(str);
}
return st.isEmpty();
}
}
My LeetCode submission :-
public boolean isValid(String s) {
Stack<Character> sc = new Stack<>();
for(int i =0;i<s.length();i++){
char ch = s.charAt(i);
if(ch == '(' || ch == '{' || ch == '['){
sc.push(ch);
}else if(ch == ')'){
if(!sc.isEmpty() && sc.peek() == '('){
sc.pop();
}else{
return false;
}
}else if(ch == '}'){
if(!sc.isEmpty() && sc.peek() == '{'){
sc.pop();
}else{
return false;
}
}else if(ch == ']'){
if(!sc.isEmpty() && sc.peek() == '['){
sc.pop();
}else{
return false;
}
}
}
if(sc.isEmpty()){
return true;
}else{
return false;
}
}
Try this.
boolean isValid(String s) {
int max = s.length(), index = 0;
char[] stack = new char[max];
for (int i = 0; i < max; ++i) {
char c = s.charAt(i);
switch (c) {
case '(': stack[index++] = ')'; break;
case '[': stack[index++] = ']'; break;
case '{': stack[index++] = '}'; break;
default:
if (index <= 0 || stack[--index] != c)
return false;
break;
}
}
return index == 0;
}
When you encounter } and the following condition fails
else if(exp.charAt(i)=='}' && !(st.isEmpty()) && st.peek()=='{') {
you should already produce an error, but you just silently ignore the incoming } and continue the iteration. So all unpaired closing parenthesis/brackets are just silently removed from your input. Instead of ([}}]) you analyze ([]) which is a balanced string, so you get no error.
Same is true for other closing characters as well.

Are there any efficient micro-optimizations to find the number of unique grid paths?

I am trying to solve this CSES problem: Grid Paths. You are given a string of length 48, and you have to find the amount of paths such that you traverse all of the grid and end up at the lower left corner.
I believe I have pruned the search to the best of my ability, as according to this book: CP Handbook (Look in the pruning the search category), the best optimization for this type of problem is to prevent your path from closing yourself off, and I have already implemented this. The time limits for this specific problem are tight, and although I have basically solved this problem, I am still failing 1-2 test cases because my solution takes around 1.01 seconds instead of being below the 1 second time limit.
Finally, I just wanted to know if there were any cool micro-optimizations I could use to marginally enhance the speed of my java code, so I could actually pass all of the test cases for this problem.
import java.io.*;
public class GridPaths {
public static class FastIO {
InputStream dis;
byte[] buffer = new byte[1 << 17];
int pointer = 0;
public FastIO(String fileName) throws Exception {
dis = new FileInputStream(fileName);
}
public FastIO(InputStream is) {
dis = is;
}
int nextInt() throws Exception {
int ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
long nextLong() throws Exception {
long ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
Integer[] readArray(int n) throws Exception {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
byte nextByte() throws Exception {
if (pointer == buffer.length) {
dis.read(buffer, 0, buffer.length);
pointer = 0;
}
return buffer[pointer++];
}
String next() throws Exception {
StringBuilder ret = new StringBuilder();
byte b;
do {
b = nextByte();
} while (b <= ' ');
while (b > ' ') {
ret.appendCodePoint(b);
b = nextByte();
}
return ret.toString();
}
}
static char[] board;
static boolean[][] visited = new boolean[7][7];
static int ans = 0;
public static boolean works(int i, int j) {
//makes sure that current spot is on the 7x7 grid and is not visited
return (i >= 0 && i<=6 && j>=0 && j<=6 && !visited[i][j]);
}
public static void solve(int i, int j, int steps) {
if (i == 6 && j == 0) {
if (steps == 48) ans++; //all spots of the grid have to be visited in order to be counted as part of the answer
return;
}
visited[i][j] = true;
//you are given ? characters in the input string, and those mean that you have to try out all 4 combinations (U,D,L,R)
if (board[steps] == '?' || board[steps] == 'L') {
//second condition of the second if statement checks if the spot directly ahead of the current spot is blocked, and if it is, the left and right spots cannot both be unvisited or else you will not continue searching
if (works(i,j-1) && !(!works(i,j-2) && works(i+1,j-1) && works(i-1,j-1))) {
solve(i, j - 1, steps + 1);
}
}
if (board[steps] == '?' || board[steps] == 'R') {
if (works(i,j+1) && !(!works(i,j+2) && works(i+1,j+1) && works(i-1,j+1))) {
solve(i, j + 1, steps + 1);
}
}
if (board[steps] == '?' || board[steps] == 'U') {
if (works(i-1,j) && !(!works(i-2,j) && works(i-1,j+1) && works(i-1,j-1))) {
solve(i - 1, j, steps + 1);
}
}
if (board[steps] == '?' || board[steps] == 'D') {
if (works(i+1,j) && !(!works(i+2,j) && works(i+1,j+1) && works(i+1,j-1))) {
solve(i + 1, j, steps + 1);
}
}
visited[i][j] = false;
}
public static void main(String[] args) throws Exception {
FastIO in = new FastIO(System.in);
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
board = in.next().toCharArray();
solve(0,0,0);
out.println(ans);
out.close();
}
}
Note: I am already using one of the fastest, if not the fastest, ways to receive input in Java, so I do not believe I can actually improve upon that.
I've been playing around with this. In addition to using a standard mechanism for reading the input file (which I suggested in a comment), you can gain a little time in the search alg itself by doing two things:
Break the case board[steps] == '?' off from the other cases. So check for board[steps] == '?' first, and just try all four directions in that case. Otherwise (the else case for if (board[steps] == '?'), just check for U/D/L/R. Since for most steps, the character will be '?', you save having to make the U/D/L/R tests most of the time.
Look up the character to be tested once, with c = board[steps],and then use c in each test instead of board[steps].
Doing these two things saved about 5% it seems. I was doing 100 reps of the solve and timing with System.currentTimeMillis(). I know there are more accurate ways of timing, but this was good enough to see a definite improvement even though the times jumped around quite a bit trial to trial. The best I ever saw in each case was 3600 millis for 100 iterations as originally written vs 3400 millis with the improvements.
My guess is that it's mostly the first change that matters. I'd expect the compiler to be doing the second already, but I didn't try the two optimizations independently.
I also solved this problem in java (AC), and here is how I did it
public static char[] defaultPath;
public static boolean[][] isUsed;
public static int counter = 0;
public static void solve(int indexChar, int indexRow, int indexColumn) {
if (indexRow == 8 && indexColumn == 2) {
if (indexChar == 48) {
counter++;
}
}else {
// Find correct way: 'D', 'U', 'L', 'R'
char correctWay = '?';
// (1) (1)
// 0 1 or 1 0
// 1 1
if ((isUsed[indexRow+1][indexColumn+1] || isUsed[indexRow+1][indexColumn-1])
&& isUsed[indexRow+2][indexColumn] && !isUsed[indexRow+1][indexColumn]) {
correctWay = 'D';
}
// 1 1
// 0 1 or 1 0
// (1) (1)
else if ((isUsed[indexRow-1][indexColumn+1] || isUsed[indexRow-1][indexColumn-1])
&& !isUsed[indexRow-1][indexColumn] && isUsed[indexRow-2][indexColumn]) {
correctWay = 'U';
}
// 1 0 (1) or 1
// 1 1 0 (1)
else if ((isUsed[indexRow+1][indexColumn-1] || isUsed[indexRow-1][indexColumn-1])
&& !isUsed[indexRow][indexColumn-1] && isUsed[indexRow][indexColumn-2]) {
correctWay = 'L';
}
//(1) 0 1 or 1
// 1 (1) 0 1
else if ((isUsed[indexRow+1][indexColumn+1] || isUsed[indexRow-1][indexColumn+1])
&& !isUsed[indexRow][indexColumn+1] && isUsed[indexRow][indexColumn+2]) {
correctWay = 'R';
}
// Check input path (default path)
char c = defaultPath[indexChar];
if (c == '?') {
if (correctWay == '?') {
// 'D'
if (!isUsed[indexRow+1][indexColumn]) {
isUsed[indexRow+1][indexColumn] = true;
solve(indexChar+1, indexRow+1, indexColumn);
isUsed[indexRow+1][indexColumn] = false;
}
// 'U'
if (!isUsed[indexRow-1][indexColumn]) {
isUsed[indexRow-1][indexColumn] = true;
solve(indexChar+1, indexRow-1, indexColumn);
isUsed[indexRow-1][indexColumn] = false;
}
// 'L'
if (!isUsed[indexRow][indexColumn-1]) {
isUsed[indexRow][indexColumn-1] = true;
solve(indexChar+1, indexRow, indexColumn-1);
isUsed[indexRow][indexColumn-1] = false;
}
// 'R'
if (!isUsed[indexRow][indexColumn+1]) {
isUsed[indexRow][indexColumn+1] = true;
solve(indexChar+1, indexRow, indexColumn+1);
isUsed[indexRow][indexColumn+1] = false;
}
}else {
if (correctWay == 'D') {
isUsed[indexRow+1][indexColumn] = true;
solve(indexChar+1, indexRow+1, indexColumn);
isUsed[indexRow+1][indexColumn] = false;
}else if (correctWay == 'U') {
isUsed[indexRow-1][indexColumn] = true;
solve(indexChar+1, indexRow-1, indexColumn);
isUsed[indexRow-1][indexColumn] = false;
}else if (correctWay == 'L') {
isUsed[indexRow][indexColumn-1] = true;
solve(indexChar+1, indexRow, indexColumn-1);
isUsed[indexRow][indexColumn-1] = false;
}else if (correctWay == 'R') {
isUsed[indexRow][indexColumn+1] = true;
solve(indexChar+1, indexRow, indexColumn+1);
isUsed[indexRow][indexColumn+1] = false;
}
}
}else {
if (c == correctWay || correctWay == '?') {
if (c == 'D' && !isUsed[indexRow+1][indexColumn]) {
isUsed[indexRow+1][indexColumn] = true;
solve(indexChar+1, indexRow+1, indexColumn);
isUsed[indexRow+1][indexColumn] = false;
}else if (c == 'U' && !isUsed[indexRow-1][indexColumn]) {
isUsed[indexRow-1][indexColumn] = true;
solve(indexChar+1, indexRow-1, indexColumn);
isUsed[indexRow-1][indexColumn] = false;
}else if (c == 'L' && !isUsed[indexRow][indexColumn-1]) {
isUsed[indexRow][indexColumn-1] = true;
solve(indexChar+1, indexRow, indexColumn-1);
isUsed[indexRow][indexColumn-1] = false;
}else if (c == 'R' && !isUsed[indexRow][indexColumn+1]) {
isUsed[indexRow][indexColumn+1] = true;
solve(indexChar+1, indexRow, indexColumn+1);
isUsed[indexRow][indexColumn+1] = false;
}
}
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
defaultPath = scanner.next().toCharArray();
isUsed = new boolean[11][11];
for (int i = 0; i < 11; i++) {
isUsed[0][i] = true;
isUsed[1][i] = true;
isUsed[9][i] = true;
isUsed[10][i] = true;
isUsed[i][0] = true;
isUsed[i][1] = true;
isUsed[i][9] = true;
isUsed[i][10] = true;
}
isUsed[2][2] = true;
isUsed[8][1] = false;
isUsed[9][2] = false;
solve(0, 2, 2);
System.out.println(counter);
scanner.close();
}

Infix to Postfix using Stacks Java

I am trying to write a program to convert an infix expression to a postfix expression.
The algorithm that I am using is as follows :
1. Create a stack
2. For each character t in the expression
- If t is an operand, append it to the output
- Else if t is ')',then pop from the stack till '(' is encountered and append
it to the output. do not append '(' to the output.
- If t is an operator or '('
-- If t has higher precedence than the top of the stack, then push t
on to the stack.
-- If t has lower precedence than top of the stack, then keep popping
from the stack and appending to the output until either stack is
empty or a lower priority operator is encountered.
After the input is over, keep popping and appending to the output until the
stack is empty.
Here is my code which prints out wrong results.
public class InfixToPostfix
{
private static boolean isOperator(char c)
{
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^'
|| c == '(' || c == ')';
}
private static boolean isLowerPrecedence(char op1, char op2)
{
switch (op1)
{
case '+':
case '-':
return !(op2 == '+' || op2 == '-');
case '*':
case '/':
return op2 == '^' || op2 == '(';
case '^':
return op2 == '(';
case '(':
return true;
default:
return false;
}
}
public static String convertToPostfix(String infix)
{
Stack<Character> stack = new Stack<Character>();
StringBuffer postfix = new StringBuffer(infix.length());
char c;
for (int i = 0; i < infix.length(); i++)
{
c = infix.charAt(i);
if (!isOperator(c))
{
postfix.append(c);
}
else
{
if (c == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
{
postfix.append(stack.pop());
}
if (!stack.isEmpty())
{
stack.pop();
}
}
else
{
if (!stack.isEmpty() && !isLowerPrecedence(c, stack.peek()))
{
stack.push(c);
}
else
{
while (!stack.isEmpty() && isLowerPrecedence(c, stack.peek()))
{
Character pop = stack.pop();
if (pop != '(')
{
postfix.append(pop);
}
}
}
stack.push(c);
}
}
}
return postfix.toString();
}
public static void main(String[] args)
{
System.out.println(convertToPostfix("A*B-(C+D)+E"));
}
}
The program should print AB*CD+-E+ but it is printing AB*-CD+E.
Why is the output incorrect ?
Also, Is there a more elegant solution to this problem. Please share if you have or know one.
Issue is with your else part:
if (!stack.isEmpty() && !isLowerPrecedence(c, stack.peek()))
{
stack.push(c);
}
else
{
while (!stack.isEmpty() && isLowerPrecedence(c, stack.peek()))
{
Character pop = stack.pop();
if (pop != '(')
{
postfix.append(pop);
}
}
}
stack.push(c);
So here you are pushing the same c element twice with stack.push() when you see stack is not empty and precedence match is higher.
So put this stack.push within else part or remove the push from if condition.
Another issue is, when at the end you have some operators within the stack you dont pop them out.
Here's the code that i came up with for your case:
private static boolean isOperator(char c)
{
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^'
|| c == '(' || c == ')';
}
private static boolean isLowerPrecedence(char op1, char op2)
{
switch (op1)
{
case '+':
case '-':
return !(op2 == '+' || op2 == '-');
case '*':
case '/':
return op2 == '^' || op2 == '(';
case '^':
return op2 == '(';
case '(':
return true;
default:
return false;
}
}
public static String convertToPostfix(String infix)
{
Stack<Character> stack = new Stack<Character>();
StringBuffer postfix = new StringBuffer(infix.length());
char c;
for (int i = 0; i < infix.length(); i++)
{
c = infix.charAt(i);
if (!isOperator(c))
{
postfix.append(c);
}
else
{
if (c == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
{
postfix.append(stack.pop());
}
if (!stack.isEmpty())
{
stack.pop();
}
}
else
{
if (!stack.isEmpty() && !isLowerPrecedence(c, stack.peek()))
{
stack.push(c);
}
else
{
while (!stack.isEmpty() && isLowerPrecedence(c, stack.peek()))
{
Character pop = stack.pop();
if (c != '(')
{
postfix.append(pop);
} else {
c = pop;
}
}
stack.push(c);
}
}
}
}
while (!stack.isEmpty()) {
postfix.append(stack.pop());
}
return postfix.toString();
}
public static void main(String[] args)
{
System.out.println(convertToPostfix("A*B-(C+D)+E"));
}
I think above answer is not correct.
This is the version corrected by me :
package Stack;
import java.util.Stack;
/*
*
Algorithm
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, output it.
3. Else,
…..3.1 If the precedence of the scanned operator is greater than the precedence of the operator in the stack(or the stack is empty), push it.
…..3.2 Else, Pop the operator from the stack until the precedence of the scanned operator is less-equal to the precedence of the operator residing on the top of the stack. Push the scanned operator to the stack.
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop and output from the stack until an ‘(‘ is encountered.
6. Repeat steps 2-6 until infix expression is scanned.
7. Pop and output from the stack until it is not empty.
*/
public class InfixToPostFixEvalution {
private static boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '(' || c == ')';
}
private static int getPrecedence(char ch) {
switch (ch) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
// A utility function to check if the given character is operand
private static boolean isOperand(char ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
public static String convertToPostfix(String infix) {
Stack<Character> stack = new Stack<Character>();
StringBuffer postfix = new StringBuffer(infix.length());
char c;
for (int i = 0; i < infix.length(); i++) {
c = infix.charAt(i);
if (isOperand(c)) {
postfix.append(c);
} else if (c == '(') {
stack.push(c);
}
// If the scanned character is an ‘)’, pop and output from the stack
// until an ‘(‘ is encountered.
else if (c == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
postfix.append(stack.pop());
}
if (!stack.isEmpty() && stack.peek() != '(')
return null;
else if(!stack.isEmpty())
stack.pop();
}
else if (isOperator(c)) // operator encountered
{
if (!stack.isEmpty() && getPrecedence(c) <= getPrecedence(stack.peek())) {
postfix.append(stack.pop());
}
stack.push(c);
}
}
while (!stack.isEmpty()) {
postfix.append(stack.pop());
}
return postfix.toString();
}
public static void main(String[] args) {
System.out.println(convertToPostfix("a+b*(c^d-e)^(f+g*h)-i"));
}
}
This code inserts the "(" as well in stack and removes accordingly. Just another way of implementing infix to postfix. Here the check is until I do not find lower priority operator in stack I will pop out the value. e.g if stack has - and next operator is +, it will pop - as it is of equal priority.
I have added custom stack implementation, however normal stack provide by java can also be used in place
import chapter4.LinkedListStack(custom stack implementation);
public class InfixToPostfix {
public String infixToPostfix(String str) {
LinkedListStack<String> stack = new LinkedListStack<>();
String[] st = str.split("");
String result = "";
for (String s : st) {
if (operator(s)) {
if (")".equals(s)) {
while (!stack.isEmpty() && !"(".equals(stack.getTop())) {
result += stack.pop();
}
if (!stack.isEmpty()) {
stack.pop();
}
} else {
if (!stack.isEmpty() && !isLowerPrecedence(s, stack.getTop())) {
stack.push(s);
} else {
while (!stack.isEmpty() && isLowerPrecedence(s, stack.getTop())) {
String top = stack.pop();
if (!"(".equals(top)) {
result += top;
}
}
stack.push(s);
}
}
} else {
result += s;
}
}
while (!stack.isEmpty()) {
result += stack.pop();
}
return result;
}
private boolean isLowerPrecedence(String s, String s1) {
switch (s) {
case "+":
return !("+".equals(s1) || "(".equals(s1));
case "-":
return !("-".equals(s1) || "(".equals(s1));
case "*":
return "/".equals(s1) || "^".equals(s1) || "(".equals(s1);
case "/":
return "*".equals(s1) || "^".equals(s1) || "(".equals(s1);
case "^":
return "(".equals(s1);
case "(":
return false;
default:
return false;
}
}
private boolean operator(String s) {
return "+".equals(s) || "-".equals(s) || "*".equals(s) || "/".equals(s) || "^".equals(s) || "(".equals(s) ||
")".equals(s);
}
public static void main(String[] args) {
InfixToPostfix itp = new InfixToPostfix();
System.out.println("The Postfix expression for A*B-(C+D)+E is: " + itp.infixToPostfix("A*B-(C+D)+E"));
System.out.println("The Postfix expression for 1+2*4/5-7+3/6 is: " + itp.infixToPostfix("1+2*4/5-7+3/6"));
System.out.println("The Postfix expression for a+(b*c)/d is: " + itp.infixToPostfix("a+(b*c)/d"));
}
}
public class LinkedListStack<E> {
private Node<E> head;
private static class Node<E> {
E item;
Node<E> next;
public Node(E item, Node<E> next) {
this.item = item;
this.next = next;
}
}
public void push(E item) {
System.out.println("push: " + item);
Node<E> newNode = new Node<>(item, null);
newNode.next = head;
head = newNode;
}
public E pop() {
if (isEmpty()) {
System.out.println("stack is Empty -> empty stack exception");
return null;
}
System.out.println("pop: " + head.item);
E data = head.item;
head = head.next;
return data;
}
public boolean isEmpty() {
return head == null;
}
public E getTop() {
return head.item;
}
}
I think the problem is here:
private static boolean isLowerPrecedence(char op1, char op2)
{
switch (op1)
{
.....
case '(':
return true;
.....
}
In the case '(', false should be returned.
This solution requires proper braces around the original expression, but its quite simple and straight forward compared to other answers I looked at. Just for someone who might need it because the post is an old post.
public static String InfixToPostfix(String origin)
{
String[] params = origin.split(" ");
Stack<String> ops = new Stack<>();
Stack<String> vals = new Stack<>();
for (int i = 0; i < params.length; i++)
{
switch (params[i]) {
case "(":
;
break;
case "+":
ops.push(params[i]);
break;
case "-":
ops.push(params[i]);
break;
case "*":
ops.push(params[i]);
break;
case "/":
ops.push(params[i]);
break;
case "sqrt":
ops.push(params[i]);
break;
// Token not operator or paren: push double value.
case ")":
String d1 = vals.pop();
String d2 = vals.pop();
String op = ops.pop();
vals.push("( " + d2 + " " + d1 + " "+ op + " )");
break;
default:
vals.push(params[i]);
break;
}
}
// System.out.print(vals.pop());
return vals.pop();
}

infix to postfix program not working [duplicate]

This question already has answers here:
Handling parenthesis while converting infix expressions to postfix expressions
(2 answers)
Closed 6 years ago.
I am supposed to write a program to convert infix to postfix. It works for some, but other times not correctly. Especially on infix expressions containing parantheses. Could anyone give me a clue why this is wrong? For example, the infix expression
( ( 5 + 5 * ( 6 - 2 ) + 4 ^ 2 ) * 8 )
returns 5562-*42^++8*((2.
import java.io.*;
import java.util.Scanner;
public class InfixToPostfix
{
//class attributes
private char curValue;
private String postfix;
private LineWriter lw;
private ObjectStack os;
//constructor
public InfixToPostfix(LineWriter l, ObjectStack o)
{
curValue = ' ';
lw=l;
os=o;
}
public String conversion(String buf)
{
String temp =" ";
StringBuffer postfixStrBuf= new StringBuffer(temp);
char popped= new Character(' ');
char topped=' ';
for (int i=0; i<buf.length(); i++)
{
curValue= buf.charAt(i);
if (curValue == '(')
os.push(curValue);
if (curValue == ')')
{
while (popped != '(')
{
popped = ((Character)os.pop());
if (popped != '(')
postfixStrBuf.append(popped);
}
}
if (isOperator(curValue))
{
if( os.isEmpty())
os.push((Character)(curValue));
else
topped=((Character)os.top());
if ( (priority(topped)) >= (priority(curValue)) && (topped != ' ') )
{
popped = ((Character)os.pop());
if (popped != '(')
postfixStrBuf.append(popped);
//if it is a left paranthess, we want to go ahead and push it anyways
os.push((Character)(curValue));
}
if ( (priority(topped)) < (priority(curValue)) && (topped != ' ') )
os.push((Character)(curValue));
}
else if (!isOperator(curValue) && (curValue != ' ') && (curValue != '(' ) && (curValue != ')' ))
postfixStrBuf.append(curValue);
}
//before you grab the next line of the file , pop off whatever is remaining off the stack and append it to
//the infix expression
getRemainingOp(postfixStrBuf);
return postfix;
//postfixStrBuf.delete(0, postfixStrBuf.length());
}
public int priority(char curValue)
{
switch (curValue)
{
case '^': return 3;
case '*':
case '/': return 2;
case '+':
case '-': return 1;
default : return 0;
}
}
public boolean isOperator(char curValue)
{
boolean operator = false;
if ( (curValue == '^' ) || (curValue == '*') || (curValue == '/') || (curValue == '+' ) || (curValue == '-') )
operator = true;
return operator;
}
public String getRemainingOp(StringBuffer postfixStrBuf)
{
char popped=' ';
while ( !(os.isEmpty()) )
{
opped = ((Character)os.pop());
postfixStrBuf.append(popped);
}
postfix=postfixStrBuf.toString();
return postfix;
}
}
I will only post how the inner loop should look like (without the castings everywhere):
if (curValue == '(') {
os.push(curValue);
} else if (curValue == ')') {
if(!os.isEmpty()) {
topped = os.pop();
while (!os.isEmpty() && (topped != '(')) {
postfixStrBuf.append(topped);
topped = os.pop();
}
}
} else if (isOperator(curValue)) {
if (os.isEmpty()) {
os.push(curValue);
} else {
while(!os.isEmpty() && (priority(os.top()) >= priority(curValue))) {
popped = os.pop();
postfixStrBuf.append(popped);
}
os.push(curValue);
}
} else if (curValue != ' ') {
postfixStrBuf.append(curValue);
}
Disclosure: it is pretty late already so I hope it is fine. You should fix the way variables are initialized and return of the getRemainingOp method.

Categories

Resources