float Calculate(const string &query)
{
std::cout << "Query: " << query << "\n";
unsigned int size = query.length();
char stack[70];
float res;
int m = 0;
for (int i = 0; i < size; i++)
{
if (query[i] >= '0' && query[i] <= '9')
{
stack[m] = query[i] - '0';
m++;
continue;
}
switch (query[i])
{
case '+':
{
res = stack[m - 2] + stack[m - 1];
break;
}
case '-':
{
res = stack[m - 2] - stack[m - 1];
break;
}
case '*':
{
res = stack[m - 2] * stack[m - 1];
break;
}
case '/':
{
res = stack[m - 2] / stack[m - 1];
break;
}
}
stack[m - 2] = res;
m--;
cout << "RES: " << res << "\n";
}
return res;
}
It calculates reverse polish notation.
When I call something like: Calculate("11+") it returns right result: 2.
But, when I pass a variable after getting of RPN string:
string inputStr;
string outputStr;
cout << "Put exercise\n";
getline(std::cin, inputStr);
outputStr = GetRPN(inputStr);
cout << "Output str :" << outputStr << ":\n";
float res = Calculate(outputStr);
std::cout << res << "\n";
So, when I input string: 1+1, function GetRPN returns 11+ and I see that in second cout. But result is 0!
What could it be?
string GetRPN(string input)
{
vector <char> operation;
string outputStr; //output string, keep RPN
int stack_count = 0;
for(int i = 0; i < input.length(); i++)
{
if(input[i] >= '0' && input[i] <= '9')
{
outputStr += input[i];
}
else
{
if(operation.empty())
{
operation.push_back(input[i]);
stack_count++;
}
else if(operation[stack_count - 1] == '+' || operation[stack_count - 1] == '-')
{
operation.push_back(input[i]);
stack_count++;
}
else if ((operation[stack_count - 1] == '*' || operation[stack_count - 1] == '/') && (input[i] == '*' || input[i] == '/'))
{
outputStr += operation[stack_count - 1]; // move mark of operation to output str
operation.pop_back(); // delet last element from vector
operation.push_back(input[i]);// plus new operation mark to vector
stack_count++;
}
else if (operation[stack_count - 1] == '*' || operation[stack_count - 1] == '/')
{
outputStr += input[i];
}
}
}
for(int i = operation.size(); i >= 0; i--)
{
outputStr += operation[i]; // move all operation marks to otput str
}
return outputStr;
}
Your cycle here
for(int i = operation.size(); i >= 0; i--)
{
outputStr += operation[i]; // move all operation marks to otput str
}
does not make any sense. You are obviously attempting to access the vector at invalid index. It is illegal to access the element at operation[i] when i is equal operation.size(). The index is out of range.
Any self-respecting implementation would immediately report this problem with an assertion. In any case, as I said in the comment, the problems like that are resolved by debugging the code. Why are you asking other people to debug your code instead of doing it yourself?
If your string has any whitespace or unprintable characters in it, you'll end up storing into stack with a negative index, which will overwrite other stuff in your stack frame and could cause anything to happen.
You should add some error checking to Calculate -- the switch should have a default that prints a sensible error message, and you should check the value of m before accessing stack[m] or stack[m-2] to make sure the stack doesn't underflow or overflow (and you should print a sensible error if it does.) You should be able to pass ANY random string to Calculate and have it tell you why its not a valid RPN expression.
Related
Our teacher gave us this exercise:
"Given a string like '-5,14' write a function that returns the float value of -5,14
I used double here just to test the precision, but it also didn't work with floats.
[also i'm from Europe, we use the comma instead of the dot. Oh also we aren't allowed to use the type string and bool, we have to "make" them like in C]
This is what i came up with, and it seems to work a little bit. Positive numbers are similar, but wrong, and given a negative number, the result is similar to 10 times the positive of the given number.
It should work like this:
I read the string into an array of characters;
I check if the first character is a minus. if so, subtract 1 from the number of integer figures because i will count them later starting from index 0;
I count the number of integer figures with a loop from the start of the array to the ',' character;
I count the number of decimal figures with a loop from after the ',' to the end of the string;
[Keep in mind for the next step that, following the ASCII table, the code for the character of a number is that number + 48]
I add to the result variable every integer figure multiplied by ten to the power of whatever place in the number it has.
I do the same for the deicmal values but with the negative exponent.
if the number was negative, i multiply the result with -1.
But for some reason it's not working properly. The lower the number is, the less accurate it is (given 4,5 the result is 9, but given 345,543 the result is 350,43)
#include <iostream>
#define EOS '\0'
#define DIM 100
#define TRUE 1
#define FALSE 0
void leggiN(char* c)
{
std::cout << "Insert a number: ";
std::cin >> c;
}
double stof(char* str)
{
double Result = 0;
double ascii_to_int = 48;
int i = 0;
int j = 0;
int IntegerDigits = 0;
int DecimalDigits = 0;
int CommaIndex;
int isNegative = FALSE;
if (str[0] == '-')
{
IntegerDigits = -1;
isNegative = TRUE;
}
while (str[i] != ',')
{
++IntegerDigits;
++i;
}
CommaIndex = i;
++i;
while (str[i] != EOS)
{
++DecimalDigits;
++i;
}
for (i = (CommaIndex - 1); i >= 0; --i)
{
Result += (str[i] - ascii_to_int) * (std::pow(10, j));
++j;
}
j = 0;
for (i = (CommaIndex + 1); str[i] != EOS; ++i)
{
Result += (str[i] - ascii_to_int) * (std::pow(10, -j));
++j;
}
if (isNegative == 1)
Result = Result * -1;
return Result;
}
int main()
{
char str[DIM];
leggiN(str);
std::cout << stof(str);
}
use j = 1 to start your second for loop. You are trying to raise 10 to the power of -0
j = 1;
for (i = (CommaIndex + 1); str[i] != EOS; ++i)
{
Result += (str[i] - ascii_to_int) * (std::pow(10, -j));
++j;
}
If your code return 9.0 when you enter "4,5", your problem has nothing to do with imprecision.
There are other problems in your code, I've tried to un it and got a SEGFAULT...
#include <iostream>
#define EOS '\0' // 0 being such a special value, there is no need to
// define a named constant for it.
#define DIM 100
#define TRUE 1 // the language defines boolean values, avoid defining
#define FALSE 0 // unnecessary named constants for something that already
// exists.
void leggiN(char* c)
{
std::cout << "Insert a number: ";
std::cin >> c; // Inserting from cin to a char* is a BIG no-no.
// some compilers won't even allow it, for good reasons
// i.e.: what is the length of the array pointed to?
}
double stof(char* str) // you are indicating that you may modify str?
{
double Result = 0;
double ascii_to_int = 48; // this is a terrible name.
int i = 0;
int j = 0;
int IntegerDigits = 0;
int DecimalDigits = 0;
int CommaIndex;
int isNegative = FALSE;
if (str[0] == '-') // is str a valid pointer? what happens if NULL ??
{
IntegerDigits = -1;
isNegative = TRUE;
// you fail to skip the sing character, should have ++i here.
}
while (str[i] != ',') // what happens if there is no ',' in the string?
{ // you should check for str[i] == 0.
++IntegerDigits;
++i;
}
CommaIndex = i;
++i;
while (str[i] != EOS)
{
++DecimalDigits; // why do you count decimal digits?
++i; // you do not use this result anyway...
}
for (i = (CommaIndex - 1); i >= 0; --i)
{
// what happens if you have non-digit characters? they participate
// in the conversion??
// you call std::pow(), but do not include <cmath> at the top of the file.
// isn't str[i] - '0' clearer ?
Result += (str[i] - ascii_to_int) * (std::pow(10, j));
++j;
}
j = 0;
for (i = (CommaIndex + 1); str[i] != EOS; ++i)
{
Result += (str[i] - ascii_to_int) * (std::pow(10, -j));
++j;
}
if (isNegative == 1) // you had defined constants fot this, but don't use them.
Result = Result * -1;
return Result;
}
int main()
{
char str[DIM];
leggiN(str);
std::cout << stof(str);
}
Here is one way to achieve what you want.
#include <iostream>
#include <string>
const char DECIMAL_POINT = ','; // we'll use a named constant here....
// usually, we'd have to check the locale
// for regional specific information.
// works like atod(), conversion stops at end of string of first illegal character.
double stof(const char* str) {
// check input, must be not null, not empty
if (!str || str[0] == 0)
return 0;
int i = 0;
bool isNegative = false;
// take care of leading sign
if (str[0] == '-' || str[0] == '+') {
isNegative = (str[0] == '-');
++i;
}
// convert integer part.
double result = 0;
while ('0' <= str[i] && str[i] <= '9') {
result = (result * 10) + (str[i] - '0');
++i;
}
// only do decimals if they are there.
if (str[i] != DECIMAL_POINT)
return (isNegative) ? -result : result;
++i; // skip decimal point
double decimals = 0;
double multiplier = .1;
while ('0' <= str[i] && str[i] <= '9') {
decimals += (str[i] - '0') * multiplier;
++i;
multiplier *= .1;
}
result += decimals;
return (isNegative) ? -result : result;
}
int main() {
// always use std::string to read strings from cin.
std::string str;
std::cout << "Insert a number: ";
std::cin >> str;
std::cout << "in: " << str << " out: " << stof(str.c_str()) << '\n';
return 0;
}
Trying to write a program to clean up a string. However for some reason I'm having problem with double spaces. Either it only removes half of the excess spaces, or it just runs forever.
char input[246] = {'\0'};
bool done = false;
int count = 0;
while (!done)
{
cout << "Hello, please enter a string to translate." << endl;
cin.get(input, 246);
}
for (int i = 0; i <= 246; i++)
{
if (input[i] != '\0')
{
count++;
}
}
for (int i = 0; i <= count - 1;) //remove double spaces
{
while (input[i] == ' ' && input[i + 1] == ' ')
{
for (int q = i + 1; q <= (count - 1) - i; q++)
{
input[q] = input[q + 1];
}
count--;
}
else
{
i++;
}
}
You can use std::unique with a custom predicate to remove duplicate spaces:
auto last = std::unique(&input[0], input + strlen(input), [](char const& a, char const &b)
{
return std::isspace(a) && std::isspace(b);
});
*last = '\0'; // Terminate string
From your algorithm, it should be
while (input[i] == ' ' && input[i + 1] == ' ')
{
for (int q = i + 1; q <= count - 1; q++) // Change that line
{
input[q] = input[q + 1];
}
count--;
}
else
{
i++;
}
but alternative solution with std::unique is the way to go.
I am solving a question which states: to change every '?' with 'a' in a string if doesn't contain if won't form consecutive 'a' else substitute with 'b', eg. a?b will be abb and not aab because here 2 a's are consecutive.
My problem is for i = 3 my string should be over- written with 'b ' according to my code it is entering into the desired block but the string does n't gets written with b, but in all the other case where it should be witten with 'a' it get's written .Help me out with these.
You can refer the problem statement from here to for better understanding my problem :https://www.hackerearth.com/practice/algorithms/greedy/basics-of-greedy-algorithms/practice-problems/algorithm/exploring-ruins/
#include <iostream>
using namespace std;
int main() {
string str;
cin >> str;
int n = str.size();
for(int i = 0; i < str.size(); i++) {
if(str[i] == '?') {
if(i == 0) {
if(str[i + 1] == 'a')
str[i] = 'b';
else
str[i] = 'a';
cout << "I am in if" << endl;
} else if(i == n - 1) {
if(str[i - 1] == 'a')
str[i] == 'b';
else
str[i] == 'a';
cout << "I am in if of else if " << endl;
} else {
if(str[i + 1] == 'a' || str[i - 1] == 'a') {
str[i] == 'b';
cout << "I am in if of else " << endl;
} else {
str[i] = 'a';
cout << "I am in else of else " << endl;
}
}
cout << str[i] << endl;
} else
continue;
}
cout << str << endl;
return 0;
}
Given string : ?ba??b
desired output : ababab
my output : aba?ab
It will be a lot easier for you if you would use functions to solve this problem.
bool check_neighbors_for_a(const string &str, size_t place) {
bool result = false;
if (place > 0) { // If there is a char before the current char
result = str[place - 1] == 'a'; // If the previous char is 'a' result become true
}
if (place < str.size() - 1) { // If there is a char after the current char
result = result || str[place + 1] == 'a'; // If the result has become true before this line, result will stay true. Else, result will be true if the next char is equal to 'a'.
// For example: b?a => result = (false || 'a' == 'a')
// For example: a?b => result = (true || 'b' == 'a')
// For example: a?a => result = (true || 'a' == 'a')
}
return result;
}
void replace_questions_by_a(string &str) {
for (size_t i = 0; i < str.size(); i++) {
if (str[i] == '?') {
if (check_neighbors_for_a(str, i)) { // If one of the neighbors is equal to 'a'
str[i] = 'b'; // Place 'b' instead of '?'
} else {
str[i] = 'a'; // Place 'a' instead of '?'
}
}
}
}
Q: Make palindromic string non-palindromic by rearranging its letters.
I just want to know why my solution is failing (wrong answer) for some test cases when i submit the code. I am sure there is an easy solution such as sorting the whole string?
void makeNonPalindrome(string& s)
{
bool ans = false;
int l = s.length();
if(l % 2 == 0)
{
for(int i = l/2; i < l; i++)
{
if(s[l/2 - 1] != s[i])
{
swap(&s[l/2 - 1],&s[i]);
ans = true;
break;
}
}
if(!ans)
{
for(int i = 0; i < l/2-1; i++)
{
if(s[l/2 - 1] != s[i])
{
ans = true;
break;
}
}
}
}
else
{
for(int i = l/2 + 1; i < l; i++)
{
if(s[l/2 - 1] != s[i])
{
swap(&s[l/2 - 1],&s[i]);
ans = true;
break;
}
}
if(!ans)
{
for(int i = 0; i < l/2-1; i++)
{
if(s[l/2 - 1] != s[i])
{
ans = true;
break;
}
}
}
if(!ans)
{
if(s[l/2] != s[0])
{
swap(&s[l/2],&s[0]);
ans = true;
}
}
}
if(ans)
cout << s << '\n';
else
cout << -1 << '\n';
}
Rearranging a palindrome so it become non-palindromic can be done quite fast, by simply trying to swap two adjacent letters in the string if they are different.
For instance, in 'bob', you'd need to find the first distinct adjacent letters (that is b and o in our case), and swap them. The result would then be 'obb', which is not a palindrome.
void makeNonPalindrome(std::string& s) {
char tmp;
for (unsigned i = 0; i < s.length() - 1; i++) {
if (s[i] != s[i+1]) { // then swap s[i] and s[i+1]
tmp = s[i];
s[i] = s[i+1];
s[i+1] = tmp;
std::cout << s << '\n';
return;
}
}
std::cout << -1 << '\n';
}
This is a simpler way to make a palindrome non palindromic.
NB: this function assumes that the input is indeed a palindrome, so if you feed it a string like 'oob', it will output 'bob' which is a palindrome.
Given the input palindrome string s you can just use find_first_not_of to determine if the string can be rearranged into a non-palindrome at all, and if so what characters should be swapped to do this. For example:
const auto foo = s.find_first_not_of(s[0], 1);
If foo == string::npos it means that there isn't a possible non-palindrome rearrangement. Otherwise swap(s[0], s[foo]) will break the palindrome.
Live Example
I have an algorithm that is supposed to take a string called str and check it against a specific rule defined as:
NOTHING comes after IX or IV.
It will print legal if the rule is not broken, and Illegal if the rule IS broken.
Here is my code that I have created:
string str = "MXCIVXX";
int length = str.length();
bool legal = true;
for (int i = 0; i < length; i++) {
if ((str[i] == 'I' && str[i + 1] == 'X') && (str[i + 2] != '/0'))
legal = false;
if ((str[i] == 'I' && str[i + 1] == 'V') && (str[i + 2] != '/0'))
legal = false;
}
if (legal == true)
cout << "Legal" << endl;
else if (legal == false)
cout << "Illegal" << endl;
I have tested multiple roman numerals in the string but it prints out legal if IX is followed by another character in the string. How can I fix this to confirm that IX or IV is not followed by another character?
You meant the null character, so '\0' instead of '/0'
Also, your approach is not accurate(read the below comments and thanks to #NathanOliver). This approach should work better:
int main()
{
std::string str = "IX";
int size = str.size();
bool legal = true;
if (str[size - 2] == 'I') // the char before the last char
{
if (str[size - 1] == 'V' || str[size - 1] == 'X') // the last char
legal = true;
else
legal = false;
}
else
legal = false;
if (legal)
std::cout << "Legal" << std::endl;
else
std::cout << "Illegal" << std::endl;
getchar();
return 0;
}
To check if "IX" or "IV" exist and if it does it is at then end of the string you can use std::string::find and check that it returns a position that is at the end of the string. So if we have a string like
std::string bad_str = "MXCIVXX";
and we use find like
std::size_t pos = bad_str.find("IV");
Then pos will either be std::string::npos meaning nothing was found or it will be the position of where it found "IV". You can check that by using
if (pos == std::string::npos || pos == bad_str.size() - 2)
std::cout << "good\n";
else
std::cout << "bad\n";
Then you just need to do this for "IX" as well. This avoids all the pitfalls that you could forget to handle in the manual version like going past then end of the string.
You can try the following code which will handle cases like "MIXCIXXIV" :
String str = "MXCIVXX";
int length = str.length();
bool legal = true;
for (int i = 0; i < length - 2; i++) {
if ((str[i] == 'I' && str[i + 1] == 'X') && length > i + 2){
legal = false;
break;
}
if ((str[i] == 'I' && str[i + 1] == 'V') && length > i + 2){
legal = false;
break;
}
}
if (legal == true)
cout << "Legal" << endl;
else if (legal == false)
cout << "Illegal" << endl;