Postfix Evaluation how to detect operator vs operand - c++

I have this Code in which I am using character array to store each expression but it doesnt work with numbers >9 my current code is:
int main(){
int i,n,c,k,l;
char buf[200];
cin>>n;
IntStack s(n);
i=0;
while(i<n)
{
cin>>buf[i];
if(buf[i]=='*')
{
k=s.pop();
l=s.pop();
k=k*l;
s.push(k);
}
else if(buf[i]=='+')
{
k=s.pop();
l=s.pop();
k=k+l;
s.push(k);
}
else if(buf[i]=='-')
{
k=s.pop();
l=s.pop();
k=l-k;
s.push(k);
}
else if(buf[i]=='/')
{
k=s.pop();
l=s.pop();
k=l/k;
s.push(k);
}
else
{
c=(buf[i]-48);
s.push(c);
}
i++;
}
k=s.pop();
if(s.isempty())
{
cout<<k;
}
else
{
cout<<"INVALID";
}
return 0;
}
Input:
11
1 2 + 3 * 6 + 2 3 + / <-Working
11
3 5 * 2 / 11 3 / 7 * + <-not Working because of 11 in input
Kindley help solving this problem or give an better logic to differentiate between numbers and operators.
Complete Code can be viewed here.

To read the input, and split it into what compiler theory calls "tokens", you need a simple lexical analyzer, or scanner, but slightly more advanced than the just-read-a-character version you have.
A technique used in the simple scanner given in (the previous edition of) the "dragon book" (Aho, Sethi, Ullman: Compilers - Principles, Techniques, and Tools, 1986) is to read a character, and if it is a digit put it back in the input (with ungetc in C), and then read an integer normally. If it is not a digit, handle it as an operator.

Before applying any operand, you are just popping one digit. There should be a loop to pop all digits until another operator is found, and concatenate the digits to make a number. For example:
1+23+3
After first '+' operator, there should be a loop to pop both 2 and 3 ( generally until next operator is found). Then convert it to number 23 and apply the operator to 1 and 23.

Related

How to find greater than a number that should be a Fascinating number ,

Fascinating Number:-
Hey find any four digit number fascinating that has all the 4 digits unique. For example 1234 is a fascinating number. His friend Rahul gave him N numbers and asks him to find the minimum number which is strictly larger than the given one and has only distinct digits.
Input format
The first line of the input contains integer N, denoting the count of numbers provided by Rahul.
Each of the next N lines contains one integer.
Output format
Print the next fascinating number.
Constraints
1<=N<=10
1000<=number<=9000
Time Limit
1 second
Example
Input
2
1234
2010
Output
1235
2013
Sample test case explanation, 1235 is the minimum number that is larger than 1234 with all 4 digits 1,2,3,5 distinct.
Please can anyone help, my approach is to take a number from user and find out all the digits and check whether they are equal or not, if they aren't equal then add +1 in the digit.
#include <iostream>
using namespace std;
int main() {
int N,num;
cin>>num;
int first_digit,second_digit,third_digit,fourth_digit;
fourth_digit=num%10;
num=num/10;
third_digit=num%10;
num=num/10;
second_digit=num%10;
num=num/10;
first_digit=num%10;
while (first_digit==second_digit || first_digit==third_digit || first_digit==fourth_digit || second_digit==first_digit||second_digit==third_digit||second_digit==fourth_digit || third_digit==first_digit|| third_digit==second_digit|| third_digit==fourth_digit || fourth_digit==first_digit || fourth_digit==second_digit || fourth_digit==third_digit)
{
if (first_digit == second_digit)
{
second_digit=second_digit+1;
}
else if(first_digit == third_digit)
{
third_digit=third_digit+1;
}
else if(first_digit == fourth_digit)
{
fourth_digit=fourth_digit+1;
}
if (second_digit == first_digit)
{
second_digit=second_digit+1;
}
else if(second_digit == third_digit)
{
third_digit=third_digit+1;
}
else if(second_digit == fourth_digit)
{
fourth_digit=fourth_digit+1;
}
if (third_digit == first_digit)
{
third_digit=third_digit+1;
}
else if(third_digit == second_digit)
{
third_digit=third_digit+1;
}
else if(third_digit == fourth_digit)
{
fourth_digit=fourth_digit+1;
}
if (fourth_digit == first_digit)
{
fourth_digit=fourth_digit+1;
}
else if(fourth_digit == second_digit)
{
fourth_digit=fourth_digit+1;
}
else if(fourth_digit == third_digit)
{
fourth_digit=fourth_digit+1;
}
}
cout<<first_digit<<second_digit<<third_digit<<fourth_digit;
return 0;
}
Their are many mistakes in the code let me point them so you check and try it yourself
Mistakes which i noticed
1.What are u exactly checking in the while condition (your intention is to check weather the number digits are unique or not but when u give a unique input then it will never go inside the while loop)
When their is a digit like 9 when u add 1 to it it becomes 10 and 10 will appended please try other approach when its 9 (hint increase the previous digit by 1 and move that 9 to zero) [example if number is 2039 you code will make it 20310 which is wrong if u try increased the before number which means 2049 and replacing 9 with 0 and again as 0 is duplicate repeat until u get unique numbers]
Hope this explanation helps!
(Remember these things(Few suggestions))
If this question is from a competition of codding post the questions after competition
If you just want direct code from here this is not the correct place!

Is cin.get() reading multiple digit characters at once?

We were asked to write a simple C++ program by our teacher to add two numbers in the following format:
input: 12 14
output: m+n = 26
The program must also work for other inputs in the form:
input: Hello please add 12 and 14 !
output: m+n = 26
The solution that was given was:
#include <iostream>
using namespace std;
int main(){
int m,n;
char ch;
while(cin.get(ch)){
if(isdigit(ch))
{
cin.putback(ch);
cin>>m;
break;
}
}
//cin.putback() restores the last character
//read by cin.get() back to the input stream
while(cin.get(ch)){
if(isdigit(ch))
{
cin.putback(ch);
cin>>n;
break;
}
}
cin.ignore(80,'\n');
cout<<"m + n = "<<m+n<<endl;
return 0;}
But now I need to know why this program also works for numbers that are not single digits. Shouldn't cin.get(char) just read one digit and cin.putback() return the same? Please help me I am a beginner.
Yes, cin.get() will read only one character at a time.
The important part, where the number is actually read, is 4 lines below: cin>>m;. This will consume as many digits as possible and store the resulting integer in m.
Some more details:
// example with input 524 42
while(cin.get(ch)) // extract one character at a time
{ // ch='5', remaining input="24 42"
if(isdigit(ch)) // if it's a digit (0-9), then:
{
cin.putback(ch); // Put it back into the stream, "unread" it
// remaining input="524 42"
cin >> m; // extract an integer from stream
// m=524, remaining input="42"
break;
}
}
The reason for the loops seems to be to skip over any non-numeric input before a number appears. Note that there is a little bug here, since it will also ignore leading signs. (e.g. input -4 4 will output m + n = 8)

Why should you include more than one value in a return statement?

I've seen instances where someone would use return statements with multiple values. For example: return 8, 10, 6; As far as I know, only one of these values will actually be returned. What is the benefit of using return this way?
Specifically, this question appears on my homework.
The statement: return 2 * 3 + 1, 1 + 5; returns the value ____.
I know it would always return 6, so why would I ever write it like this?
Forgive me if this is a simple question. I am still somewhat new to programming.
The statement return 2 * 3 + 1, 1 + 5; returns the value 6.
This the trick of comma operator in C++. You can read more about it here:
https://en.cppreference.com/w/cpp/language/operator_other
A comma operator is basically a list of expressions separated by commas, they will be evaluated from left to right, and the result of the last item will be treated as the result of the whole comma operator.
Here is a simple example demonstrating how comma operator works.
int foo() {
int i = 1;
return i += 2, i++, i + 5; // This is a comma operator with three items
// i += 2 will be evaluated first, then i == 3
// i++ will be evaluated second, then i == 4
// i + 5 will be evaluate last, and the result is 9
// the result of the last item is returned by the return statement
}
int main() {
std::cout << foo();
return 0;
}
This code prints 9.
When you do this you are avoiding using math in your function block and this make your function like working 3 time and result would be the one you want

Keeping the order of operations while doing a sequential calculation

I am spending my evening doing some programming problems from Kattis. There is one part of the problem 4 thought that I am stuck on.
Given a number, the program is supposed to return the operations (+, -, * or /) required between 4 fours to achieve that number.
For example, the input
9
would result in the output
4 + 4 + 4 / 4 = 9
My solution (not efficient, but simple) is to evaluate all possible ways to combine the operators above and see if any of the combinations achieve the wanted result.
To do this I have written the function seen below. It takes in an array of chars which are the operators to be evaluated (uo[3], could look like {+, /, *}), and the wanted result as an integer (expRes).
bool check(char uo[3], int expRes) {
int res = 4;
for(int oPos = 2; oPos >= 0; oPos--) {
switch (uo[oPos]) {
case '+' : res += 4; break;
case '-' : res -= 4; break;
case '*' : res *= 4; break;
case '/' : res /= 4; break;
}
}
return res == expRes;
}
I realized that this "sequential" approach comes with a problem: it doesn't follow the order of operations. If I was to call the function with
uo = {+, -, /}
and
expRes = 7 it would return false since 4 + 4 = 8, 8 - 4 = 4, 4 / 4 = 1.
The real answer is obviously true, since 4 + 4 - 4 / 4 = 7.
Can any of you think of a way to rewrite the function so that the evaluation follows the order of operations?
Thanks in advance!
Its an easy problem if you look at it.
You are restricted with four 4's and three operators in between, that is you already know your search space. So one solution is to generate the complete search space which is O(n^3) = 4^3 = 64 total equations, where n is the number of operators. Keep the answer to these solutions as a <key, value> pair so that look up to the input of test case is O(1).
Step wise you'd do.
Generate Complete Sequence and store them as key, value pairs
Take Input from test cases
Check if key exists, if yes print the sequence, else print that the sequence doesn't exist
Solution would take 64*1000 operations, which can easily be computed with in a second and would avoid Time Limit Exceeded Error that usually these competitions have
in Code form (most of it is incomplete):
// C++ Syntax
map<int, string> mp;
void generateAll() {
// generate all equations
}
void main () {
generateAll();
int n, t; scanf("%d", &t);
while (t--) {
scanf("%d", &n);
if ( mp.find(n) != mp.end() )
// equation exists to the input
else
// equation doesn't exist for the input
}
}

Recursive Binary Conversion C++

I am fairly new to C++. I am trying to write a recursive binary function. The binary output needs to be 4 bits, hence the logic around 15 and the binary string length. It converts to binary correctly, the problem I am having is ending the recursive call and returning the binary string to the main function. It seems to just backwards through the call stack? Can someone help me understand what is going on?
Assuming using namespace std. I know this is not good practice, however it is required for my course.
string binary(int number, string b){
if (number > 0 && number < 15){
int temp;
temp = number % 2;
b = to_string(temp) + b;
number = number / 2;
binary(number, b);
}
else if (number > 15){
b = "1111";
number = number - 15;
binary(number, b);
}
else if (number == 15){
b = "11110000";
return b;
}
//should be if number < 1
else{
int s = b.size();
//check to make sure the binary string is 4 bits or more
if (s >= 4){
return b;
}
else{
for (int i = s; i < 4; i++){
b = '0' + b;
}
return b;
}
}
}
You have your function returning a string, but then you require the user to supply an initialized string for you, and you throw away the return value except for the base cases of 15 and 0. The rest of the time, your actual communication is using the parameter b. This multiple communication will cause some headaches.
I also note that you return a properly padded 4-bit number in normal cases; however, you force a return an 8-bit 15 for the exact value 15. Is this part of the assignment specification?
The logic for larger numbers is weird: if the amount is more than 15, you return "1111" appended to the representation for the remainder. For instance, 20 would return as binary(5) followed by "1111", or "1011111", which is decidedly wrong. Even stranger, it appears that any multiple of 15 will return "11110000", since that clause (== 15) overwrites any prior value of b.
I suggest that you analyze and simplify the logic. There should be two cases:
(BASE) If number == 0, return '0'
(RECUR) return ['1' (for odd) else '0'] + binary(number / 2)
You also need a top-level wrapper that checks the string length, padding out to 4 digits if needed. If the "wrapper" logic doesn't fit your design ideas, then drop it, and work only with the b parameter ... but then quit returning values in your other branches, since you don't use them.
Does this get you moving?