Postfix evaluation method in Java - data-structures

So I tried writing a code for postfix evaluation method and it is giving me the most outrageous results.
the post fix expression I entered was "92*3+4-" and by my calculation the answer should be 17. Instead I am getting 2849. What is going on?
public static int postFixEvaluator(String s){
NewStack stack=new NewStack();
for(int i=0;i<s.length();i++){
if(Character.isDigit(s.charAt(i))) stack.push(s.charAt(i));
else if(s.charAt(i)=='+'){
int y=stack.pop();
int x=stack.pop();
int z=(int)(x+y);
stack.push((char)(z));
//System.out.println(z);
}
else if(s.charAt(i)=='-'){
int y=stack.pop();
int x=stack.pop();
int z=x-y;
stack.push((char)(z));
}
else if(s.charAt(i)=='*'){
int y=stack.pop();
int x=stack.pop();
int z=x*y;
stack.push((char)(z));
System.out.println(x*y);
}
else if(s.charAt(i)=='/'){
int y=stack.pop();
int x=stack.pop();
int z=x/y;
stack.push((char)(z));
}
else if(s.charAt(i)=='%'){
int y=stack.pop();
int x=stack.pop();
int z=x%y;
stack.push((char)(z));
}
}
return stack.pop();
}
enter code here

The basic problem is that you're pushing characters and popping integers. That is, you have:
if(Character.isDigit(s.charAt(i))) stack.push(s.charAt(i));
So if the character is 3, you'll push 3 on the stack.
But when you pop, you have:
int y=stack.pop();
The integer representation of the character 3 is 51.
It gets worse when you push results back onto the stack. If you have the characters 3 and 4 on the stack, you end up adding 51 and 52, and pushing 103 back onto the stack. But at some point you overflow the size of a character and things go completely off the rails.
My suggestion is that you create a stack of integers, and push integers onto the stack. So your statement above becomes:
if(Character.isDigit(s.charAt(i)))
{
stack.push(Character.GetNumericValue(s.charAt(i)));
}
And in the code for your operations, replace
stack.push((char)(z));
with
stack.push(z);

Related

Write a program using stack operations, which accepts a non-negative base 10 integer as a parameter, and display binary representation of number

Write a program using stack operations, which accepts a non-negative base 10 integer as a parameter, and display binary representation of number. I am getting error in my main that been trying to understand but no success so far , rest all the logic works but adding the remainder (node r) function is primarily the issue
and code is :
# include<iostream>
using namespace std;
class ListStack{
private:
struct node
{
int num;
node *next;
}*top;
public:
ListStack()
{
top= NULL;
}
void push(node n);
void pop();
void display();
};
void ListStack::push(node n)
{
node *newNode;
newNode= new node;
// cout<<"Enter number to add on stack";
// cin>>newNode->num;
newNode->num;
newNode->next=top;
top=newNode;
}
void ListStack::display()
{
node *n;
n= new node;
n=top;
while(n!=NULL){
cout << n->num<<" ";
n= n-> next;
}
}
int main(){
ListStack l;
int a;
cout<<"Enter a digit with base 10 : ";
cin>>a;
cout<<"\nbinary of entered num is : \n";
node *r;
r= new node;
while(a!=0){
a%2=r->num;
push(r);
cout<<r->num;
a/=2;
}
}

Count of subsetsum problem, how to debug where the solution is not working?

So I'm trying to solve this problem :
Given an array arr[] of integers and an integer sum, the task is to
count all subsets of the given array with a sum equal to a given sum.
Note: Answer can be very large, so, output answer modulo 10^9+7
Now this is the solution I'm trying out here:
class Solution{
private:
vector<vector<int>> t;
public:
Solution() {
t.resize(1001, vector<int> (1001,-1));
}
int perfectSum(int arr[], int n, int sum)
{
long long int result = fmod(sumrecursive(arr, n, sum),(pow(10,9)+7));
return result;
}
long long int sumrecursive(int arr[], int n, int sum){
if(sum==0){
return 1;
}
if(n==0){
return 0;
}
if(t[n][sum] != -1){
return t[n][sum];
}
if(arr[n-1]>sum){
return t[n][sum] = sumrecursive(arr, n-1, sum);
} else {
return t[n][sum] = sumrecursive(arr,n-1, sum-arr[n-1]) + sumrecursive(arr, n-1, sum);
}
}
};
Now this code is not working after some certain input:
I don't know on how to proceed in solving this problem at this point. Ideally according to the code I have written the input is within the grasp of the code and output should've been correct but unfortunately it is not the case. I wanted to ask if someone could spot on where the problem might be in the code or guide me on how to debug where the problem is in the code.
You are probably encountering integer overflow along the way.
You are taking the mod only right before ending the function, but your cache is of type int, so when placing too big numbers - you are losing some data due to overflow.

How to determine the smaller and greater value based on user input?

I am trying to write a program that determines the smaller and greater value based on user input. But I am not sure how to do this. The integer values are stored into variables named val1 and val2. So the user enters a value into each of the variables, and I want the program to determine what is the smaller and larger number.
This is what my code currently looks like:
int main()
{
int val1;
int val2;
cout<< "enter an integer followed by enter twice,\n";
cin>> val1 >> val2;
}
}
I think this is what you are looking for :
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a, b, big;
cout<<"Enter two number : ";
cin>>a>>b;
if(a>b)
{
big=a;
}
else
{
big=b;
}
cout<<"Biggest of the two number is "<<big;
getch();
}
Another way of finding the greater value.
#include<conio.h>
void main()
{
clrscr();
int a, b, big;
cout<<"Enter two number : ";
cin>>a>>b;
cout<<"Biggest of the two number is "<<a>b?a:b; // ternary operator is used instead of checking with if condition.
getch();
}
You can also try to use std::max (http://www.cplusplus.com/reference/algorithm/max/).

spoj ACPC10D -Why i am getting the wrong answer?

Here's my code .It is passing the testcase given in the problem statement.
Link for problem :http://www.spoj.com/problems/ACPC10D/
tri[i][j] stores the min value to reach at index (i,j) from tri[0][1].
//trigraphs-dp
#include<iostream>
#include<limits.h>
using namespace std;
int tri[1000000][3];
int min(int a,int b)
{
if(a<=b)
return a;
else
return b;
}
int main()
{
int n,t=1;
while(cin>>n)
{
if(n==0)
break;
for(int i=0;i<n;i++)
for(int j=0;j<3;j++)
cin>>tri[i][j];
tri[0][0]=INT_MAX;
tri[0][2]=tri[0][1]+tri[0][2];
//cout<<tri[0][2];
int a,b,c,d;
for(int i=1;i<n;i++)
for(int j=0;j<3;j++)
{
a=tri[i-1][j];
b=(j==2)?INT_MAX:tri[i-1][j+1];
c=(j==0)?INT_MAX:tri[i-1][j-1];
d=(j==0)?INT_MAX:tri[i][j-1];
tri[i][j]+=min(min(a,b),min(c,d));
}
cout<<t<<". "<<tri[n-1][1]<<"\n";
}
return 0;
}
1- You forgot to increment t in the end of the loop
2- Define tri as long long type because of possible overflow when you add up numbers.

What would be the datastructure in following scenario? (Stack with maximum)

Please note that there is no limitation of memory.
I need to insert int from 1 to 1000.
I can do the each of the following operations in constant order of time:
push():adds to the top
pop():removes the top element
getMax(): returns the max element
Please suggest me appropriate datastructure.
Since there is no limitation of memory, I will use 2 vectors - one for the actual data on the stack, and the other to keep track of the max at every state of the stack.
For simplicity sake I'm assuming this stack holds only +ve ints.
I know this doesn't have any error checking. But I am just providing the data structure idea here, not the full-fledged solution.
class StackWithMax
{
public:
StackWithMax() : top(-1), currentMax(0) { }
void push(int x);
int pop();
int getMax() { return m[top]; }
private:
vector<int> v; // to store the actual elements
vector<int> m; // to store the max element at each state
int top;
int currentMax;
};
void StackWithMax::push(int x)
{
v[++top] = x;
m[top] = max(x, currentMax);
}
int StackWithMax::pop()
{
int x = v[top--];
currentMax = m[top];
return x;
}
Use normal stack structure and additional array for counters
int c[1..1000] and variable int maxVal=0.
In code add actions after stack operations:
On push(x) -> c[x]++ ; maxVal = max(x,maxVal)
On pop():x -> c[x]-- ; if (c[x] == 0) { j=x; while(c[--j] == 0); maxVal = j; }
maxVal should have always maximum value.
Maybe I am wrong, this should have amortized computational complexity O(1).
It has been a long time since I have been analysing algorithms.

Resources