Unexpected output in C++ - c++

This is not a problem with programming contest but with the language C++.
There is an old programming problem on codeforces. The solution is with C++. I already solved in Python but I don't understand this behavior of C++. In my computer and on onlinegdb's C++ compiler, I get expected output but on codeforces judge, I get a different output.
If interested in the problem : http://codeforces.com/contest/8/problem/A
It's very simple and a small read. Though Reading it is not required for the question.
Task in Short:
Print("forward") if string a is found in string s and string b is also found in s
Print("backward") if string a is found in reverse of string s and string b is also found in reverse of s
Print("both") if both of above are true
Print("fantasy") if both of above are false
#include<bits/stdc++.h>
using namespace std;
#define int long long
//initializing all vars because blogs said uninitialized vars sometimes give unexpected result
string s="", a="", b="";
bool fw = false;
bool bw = false;
string now="";
string won="";
int pa=-1, pb=-1, ra=-1, rb=-1;
signed main()
{
//following 2 lines can be ignored
ios_base::sync_with_stdio(false);
cin.tie(NULL);
//taking main input string s and then two strings we need to find in s are a & b
cin >> s >> a >> b;
//need reverse string of s to solve the problem
string r = s;
reverse(r.begin(), r.end());
//pa is index of a if a is found in s else pa = -1 if not found
pa = s.find(a);
//if a was a substring of s
if (pa != -1) {
//now is substring of s from the next letter where string a was found i.e. we remove the prefix of string till last letter of a
now = s.substr(pa + a.size(), s.size() - (pa + a.size()));
//pb stores index of b in remaining part s i.e. now
pb = now.find(b);
//if b is also in now then fw is true
if (pb != -1) {
fw = true;
}
}
//same thing done for the reverse of string s i.e. finding if a and b exist in reverse of s
ra = r.find(a);
if (ra != -1) {
won = r.substr(ra + a.size(), r.size() - (ra + a.size()));
rb = won.find(b);
if (rb != -1) {
bw = true;
}
}
if (fw && bw) {
cout << "both" << endl;
}
else if (fw && !bw) {
cout << "forward" << endl;
}
else if (!fw && bw) {
cout << "backward" << endl;
}
else {
cout << "fantasy" << endl;
}
return 0;
}
For input
atob
a
b
s="atob", a="a", b="b"
Here reverse of atob is bota.
a is in atob.
So, string now = tob.
b is in tob so fw is true.
Now a is in bota.
So, string won = "" (empty because nothing after a). So, b is not in won.
So, rw is false.
Here answer is to print forward and in C++14 on my PC and onlinegdb, the output is forward but on codeforces judge, it's both.
I did many variations of the code but no result.
Finally I observed that if I run my program on PC and don't give any input and terminate the program in terminal with Ctrl-C, it prints both which is strange as both should only be printed when both fw and rw are true.
What is this behavior of C++?

Let's dissect this code and see what problems we can find. It kind of tips over into a code review, but there are multiple problems in addition to the proximate cause of failure.
#include<bits/stdc++.h>
Never do this. If you see it in an example, you know it's a bad example to follow.
using namespace std;
Fine, we're not in a header and brevity in sample code is a reasonable goal.
#define int long long
Oh no, why would anyone ever do this? The first issue is that preprocessor replacement is anyway prohibited from replacing keywords (like int).
Even without that prohibition, this later line
int pa=-1, pb=-1, ra=-1, rb=-1;
is now a deliberate lie, as if you're obfuscating the code. It would have cost nothing to just write long long pa ... if that's what you meant, and it wouldn't be deceptive.
//initializing all vars because blogs said uninitialized vars sometimes give unexpected result
string s="", a="", b="";
But std::string is a class type with a default constructor, so it can't be uninitialized (it will be default-initialized, which is fine, and writing ="" is just extra noise).
The blogs are warning you about default initialization of non-class types (which leaves them with indeterminate values), so
bool fw = false;
is still sensible.
NB. these are globals, which are anyway zero-initialized (cf).
signed main()
Here are the acceptable faces of main - you should never type anything else, on pain of Undefined Behaviour
int main() { ... }
int main(int argc, char *argv[]) { ... }
Next, these string positions are both (potentially) the wrong type, and compared to the wrong value:
ra = r.find(a);
if (ra != -1) {
could just be
auto ra = r.find(a);
if (ra != std::string::npos) {
(you could write std::string::size_type instead of auto, but I don't see much benefit here - either way, the interface, return type and return values of std::string::find are well-documented).
The only remaining objection is that none of now, won or the trailing substring searches correspond to anything in your problem statement.

The above answer and comments are way more enough information for your question. I cannot comment yet so I would like to add a simplified answer here, as I'm also learning myself.
From the different outputs on different compilers you can trackback the logic and found the flow of code is differ in this line:
if (rb != -1) {
Simply adding a log before that line, or using a debugger:
cout << "rb:" << rb << endl;
You can see that on your PC: rb:-1
But on codeforces: rb:4294967295
won.find(b) return npos, which mean you have an assignment: rb = npos;
This is my speculation, but a possible scenario is:
On your PC, rb is compiled as int (keyword), which cannot hold 4294967295, and assigned to -1.
But on codeforces, rb is compiled as long long, follow the definition, and 4294967295 was assigned instead.
Because you redefine the keyword int, which is advised again by standard of C++ programming language, different compiler will treat this line of code differently.

Related

How to count assignment operators in a text file?

My task is to create a program in C ++ that processes a text file in sequential mode. The data must be read from the file one line at a time. Do not back up the entire contents of the file to RAM. The text file contains syntactically correct C++ code and I have to count how many assignment operators are there.
The only thing I could think of was making a function that searches for patterns and then counts how many times they appear. I insert every assignment operator as a pattern and then sum all the counts together. But this does not work because if I insert the pattern "=" many operators such as "%=" or "+=" also get counted in. And even operators like "!=" or "==" get counted, but they shouldn't because they are comparison operators.
My code gives the answer 7 but the real answer should be 5.
#include <iostream>
#include <fstream>
using namespace std;
int patternCounting(string pattern, string text){
int x = pattern.size();
int y = text.size();
int rez = 0;
for(int i=0; i<=y-x; i++){
int j;
for(j=0; j<x; j++)
if(text[i+j] !=pattern[j]) break;
if(j==x) rez++;
}
return rez;
}
int main()
{
fstream file ("test.txt", ios::in);
string rinda;
int skaits=0;
if(!file){cout<<"Nav faila!"<<endl; return 47;}
while(file.good()){
getline(file, rinda);
skaits+=patternCounting("=",rinda);
skaits+=patternCounting("+=",rinda);
skaits+=patternCounting("*=",rinda);
skaits+=patternCounting("-=",rinda);
skaits+=patternCounting("/=",rinda);
skaits+=patternCounting("%=",rinda);
}
cout<<skaits<<endl;
return 0;
}
Contents of the text file:
#include <iostream>
using namespace std;
int main()
{
int z=3;
int x=4;
for(int i=3; i<3; i++){
int f+=x;
float g%=3;
}
}
Note that as a torture test, the following code has 0 assignments on older C++ standards and one on newer ones, due to the abolition of trigraphs.
// = Torture test
int a = 0; int b = 1;
int main()
{
// The next line is part of this comment until C++17 ??/
a = b;
struct S
{
virtual void foo() = 0;
void foo(int, int x = 1);
S& operator=(const S&) = delete;
int m = '==';
char c = '=';
};
const char* s = [=]{return "=";}();
sizeof(a = b);
decltype(a = b) c(a);
}
There are multiple issues with the code.
The first, rather mundane issue, is your handling of file reading. A loop such as while (file.good()) … is virtually always an error: you need to test the return value of getline instead!
std::string line;
while (getline(file, line)) {
// Process `line` here.
}
Next, your patternCounting function fundamentally won’t work since it doesn’t account for comments and strings (nor any of C++’s other peculiarities, but these seem to be out of scope for your assignment). It also doesn’t really make sense to count different assignment operators separately.
The third issue is that your test case misses lots of edge cases (and is invalid C++). Here’s a better test case that (I think) exercises all interesting edge cases from your assignment:
int main()
{
int z=3; // 1
int x=4; // 2
// comment with = in it
"string with = in it";
float f = 3; // 3
f = f /= 4; // 4, 5
for (int i=3; i != 3; i++) { // 6
int f=x += z; // 7, 8
bool g=3 == 4; // 9
}
}
I’ve annotated each line with a comment indicating up to how many occurrences we should have counted by now.
Now that we have a test case, we can start implementing the actual counting logic. Note that, for readability, function names generally follow the pattern “verb subject”. So instead of patternCounting a better function name would be countPattern. But we won’t count arbitrary patterns, we will count assignments. So I’ll use countAssignments (or, using my preferred C++ naming convention: count_assignments).
Now, what does this function need to do?
It needs to count assignments (incl. initialisations), duh.
It needs to discount occurrences of = that are not assignments:
inside strings
inside comments
inside comparison operators
Without a dedicated C++ parser, that’s a rather tall order! You will need to implement a rudimentary lexical analyser (short: lexer) for C++.
First off, you will need to represent each of the situations we care about with its own state:
enum class state {
start,
comment,
string,
comparison
};
With this in hand, we can start writing the outline of the count_assignments function:
int count_assignments(std::string const& str) {
auto count = 0;
auto state = state::start;
auto prev_char = '\0';
for (auto c : str) {
switch (state) {
case state::start:
break;
case state::comment:
break;
case state::string:
break;
case state::comparison:
break;
}
prev_char = c;
}
// Useful for debugging:
// std::cerr << count << "\t" << str << "\n";
return count;
}
As you can see, we iterate over the characters of the string (for (c : str)). Next, we handle each state we could be currently in.
The prev_char is necessary because some of our lexical tokens are more than one character in length (e.g. comments start by //, but /= is an assignment that we want to count!). This is a bit of a hack — for a real lexer I would split such cases into distinct states.
So much for the function skeleton. Now we need to implement the actual logic — i.e. we need to decide what to do depending on the current (and previous) character and the current state.
To get you started, here’s the case state::start:
switch (c) {
case '=':
++count;
state = state::comparison;
break;
case '<': case '>': case '!':
state = state::comparison;
break;
case '"' :
state = state::string;
break;
case '/' :
if (prev_char == '/') {
state = state::comment;
}
break;
}
Be very careful: the above will over-count the comparison ==, so we will need to adjust that count once we’re inside case state::comparison and see that the current and previous character are both =.
I’ll let you take a stab at the rest of the implementation.
Note that, unlike your initial attempt, this implementation doesn’t distinguish the separate assignment operators (=, +=, etc.) because there’s no need to do so: they’re all counted automatically.
The clang compiler has a feature to dump the syntax tree (also called AST). If you have syntactically correct C++ code (which you don't have), you can count the number of assignment operators for example with the following command line (on a unixoid OS):
clang++ -Xclang -ast-dump -c my_cpp_file.cpp | egrep "BinaryOperator.*'='" | wc -l
Note however that this will only match real assigments, not copy initializations, which also can use the = character, but are something syntactically different (for example an overloaded = operator is not called in that case).
If you want to count the compound assignments and/or the copy initializations as well, you can try to look for the corresponding lines in the output AST and add them to the egrep search pattern.
In practice, your task is incredibly difficult.
Think for example of C++ raw string literals (you could have one spanning dozen of source lines, with arbitrary = inside them). Or of asm statements doing some addition....
Think also of increment operators like (for some declared int x;) a x++ (which is equivalent to x = x+1; for a simple variable, and semantically is an assignment operator - but not syntactically).
My suggestion: choose one open source C++ compiler. I happen to know GCC internals.
With GCC, you can write your own GCC plugin which would count the number of Gimple assignments.
Think also of Quine programs coded in C++...
NB: budget months of work.

Google Kickstart - Wrong answer if cout.clear() is not used

I find this very stupid to ask, but I've been trying a question on Google Kickstart (Round A, 2021).
Now, firstly, I'd like to clarify that I do NOT need help with the question itself, but I'm encountering a weird issue that seems to be compiler-related. This problem only arises on certain compilers.
I am posting the question link, then the question statement if someone does not wish to use the link, then the problem I'm facing along with the code that works and the code that doesn't work.
Question Title: K-Goodness String, Round A (2021)
Question Link: https://codingcompetitions.withgoogle.com/kickstart/round/0000000000436140/000000000068cca3
Problem
Charles defines the goodness score of a string as the number
of indices i such that Si ≠ SN−i+1 where 1≤i≤N/2 (1-indexed). For
example, the string CABABC has a goodness score of 2 since S2 ≠ S5 and
S3 ≠ S4.
Charles gave Ada a string S of length N, consisting of uppercase
letters and asked her to convert it into a string with a goodness
score of K. In one operation, Ada can change any character in the
string to any uppercase letter. Could you help Ada find the minimum
number of operations required to transform the given string into a
string with goodness score equal to K?
Input
The first line of the input gives the number of test cases, T. T
test cases follow.
The first line of each test case contains two integers N and K. The
second line of each test case contains a string S of length N,
consisting of uppercase letters.
Output
For each test case, output one line containing Case #x: y,
where x is the test case number (starting from 1) and y is the minimum
number of operations required to transform the given string S into a
string with goodness score equal to K.
Sample Input:
2
5 1
ABCAA
4 2
ABAA
Sample Output:
Case #1: 0
Case #2: 1
Explanation:
In Sample Case #1, the given string already has a goodness score of 1. Therefore the minimum number of operations required is 0.
In Sample Case #2, one option is to change the character at index 1 to B in order to have a goodness score of 2. Therefore, the minimum number of operations required is 1.
The issue:
The problem is fairly straightforward, however, I seem to be getting a wrong answer in a very specific condition, and this problem only arises on certain compilers, and some compilers give the correct answer for the exact same code and test cases.
The specific test case:
2
96 10
KVSNDVJFYBNRQPKTHPMMTZBHQPZYQHEEEQFQWOJHPHFBFXGFFGXFBFHPHJOWQFQEEEHQYZPQHBZTMMPHTKPQRNBYFFVDNXIX
95 7
CNMYPKORAUTSYETNXAZQZGBFSJJNMOMINYKNTMHTARUMDXAJAXDMURATHMTNKYNIMOMNJJSFBGZQZAXNTEYSTUAROKPKJCD
Expected Output:
Case #1: 6
Case #2: 3
The problem arises when I do NOT use std::cout.clear() at a very specific place in my code. Just printing the value of any random variable also seems to solve this issue, it doesn't necessarily have to be cout.clear() only. I'm pasting the codes below.
**Original Code (Gives incorrect answer):**
//
// main.cpp
// Google Kickstart - Round A (2021)
//
// Created by Harshit Jindal on 10/07/21.
//
#include <iostream>
#define endl "\n"
using namespace std;
int main() {
int num_test_cases;
cin >> num_test_cases;
for (int test_case = 1; test_case <= num_test_cases; test_case++) {
int answer = 0;
int N, K;
cin >> N >> K;
char s[N];
cin >> s;
int current_goodness = 0;
for (int i = 0; i < N/2; i++) {
if (s[i] != s[N-1-i]) { current_goodness++; }
}
answer = abs(current_goodness - K);
cout << "Case #" << test_case << ": " << answer << endl;
}
return 0;
}
Incorrect Result for original code:
Case #1: 6
Case #2: 6
Modified Code (With cout.clear() which gives correct answer):
//
// main.cpp
// Google Kickstart - Round A (2021)
//
// Created by Harshit Jindal on 10/07/21.
//
#include <iostream>
#define endl "\n"
using namespace std;
int main() {
int num_test_cases;
cin >> num_test_cases;
for (int test_case = 1; test_case <= num_test_cases; test_case++) {
int answer = 0;
int N, K;
cin >> N >> K;
char s[N];
cin >> s;
int current_goodness = 0;
for (int i = 0; i < N/2; i++) {
if (s[i] != s[N-1-i]) {
current_goodness++;
}
cout.clear();
}
answer = abs(current_goodness - K);
cout << "Case #" << test_case << ": " << answer << endl;
}
return 0;
}
Correct Result for modified code:
Case #1: 6
Case #2: 3
A few additional details:
This issue is NOT coming up on my local machine, but on Google Kickstart's Judge with C++17 (G++).
Answer for Case #2 should be 3, and NOT 6.
This issue does NOT come up if only the second test case is executed directly, but only if executed AFTER test case #1.
The issue is ONLY resolved if the cout.clear() is placed within the for loop, and nowhere else.
We don't necessarily have to use cout.clear(), any cout statement seems to fix the issue.
I know it's a long question, but given that a problem is only coming up on certain machines, I believe it would require a deep understanding of c++ to be able to understand why this is happening, and hence posting it here. I'm curious to understand the reasoning behind such a thing.
Any help is appreciated.
As pointed out by Paddy, Sam and Igor in the comments, here is the solution as I understand it:
The problem arises because char s[N] is NOT C++ standard, any variable length arrays, for that matter. That might cause a buffer overrun, and will write over memory outside of the array, causing all sorts of weird behaviour.
The best way to avoid these kinds of bugs is to make it logically impossible for them to happen. – Sam Varshavchik
In this case, using string s solved the issue without having to call cout.clear().
Also, using #define endl "\n" might be faster when redirecting output to files, but since we're importing the entire std namespace, any person who does std::cout will get an error because it'll essentially get translated to std::"\n" which does not make sense.

c_str() is only reading half of my string, why? How can I fix this? Is it a byte issue?

I am writing a client program and server program. On the server program, in order to write the result back to the client, I have to convert the string to const char* to put it in a const void* variable to use the write() function. The string itself is outputting the correct result when I checked, but when I use the c_str() function on the string, it is only outputting up until the first variable in the string. I am providing some code for reference (not sure if this is making any sense).
I have already tried all sorts of different ways to adjust the string, but nothing has worked yet.
Here are how the variables have been declared:
string final;
const void * fnlPrice;
carTable* table = new carTable[fileLength];
Here is the struct for the table:
struct carTable
{
string mm; // make and model
string hPrice; // high price
string lPrice; // low price
};
Here is a snipped of the code with the issue, starting with updating the string variable, final, with text as well as the resulting string variables:
final = "The high price for that car is $" + table[a].hPrice + "\nThe low
price for that car is $" + table[a].lPrice;;
if(found = true)
{
fnlPrice = final.c_str();
n = write(newsockfd,fnlPrice, 200);
if (n < 0)
{
error("ERROR writing to socket");
}
}
else
{
n = write(newsockfd, "That make and model is not in
the database. \n", 100);
if (n < 0)
{
error("ERROR writing to socket");
}
}
Unfortunately your code does not make any sense. And that may be your major problem. You should rewrite you code end eliminate the bugs.
Switch on all compiler warnings and eliminate the warnings.
Do not use new and pointers. Never
Do not use C-Style arrays. So, something with []. Never. Use STL containers
Always initialize all variables. Always. Even if you assign an other value in the next line
Do not use magic constants like 200 (The size of the string is final.size())
If an error happens then print the error text with strerror (or a compatible function)
Make sure that your array itself and the array values are initalized
To test your function, write to socket 1 (_write(1,fnlPrice,final.size()); 1 is equal to std::cout
There is no need to use the void pointer. You can use n = _write(newsockfd, final.c_str(), final.size()); directly
If you want a detailed answer here on SO then you need to post your compiled code. I have rewritten your function and tested it. It works for me and prints the complete string. So, there is a bug in an other part of your code that we cannot not see.

creating a function to match a string in the main

This is a group assignment and it's become rather difficult to the point our professor has extended the project by 1 week. there are 50 stages/tests, we've only been able to reach up to stage 11 and then the function fails.
this function is in our .cpp file (we're positive it's this function causing the problem's because when we change parts of it, it affects stage 11 which we've passed).
int segment::match(const char word[]) {
int i;
cout << data[0];
data[0] == "OOP";
cout << data[0];
for(i=0;i<NUM_MAX;i++) {
cout << "word = " << &word[i] << " data[i] = " << data[i];
if(strstr(&word[i],data[i])!= NULL)
break;
}
return i==NUM_MAX ? 1 : i-1;
and from the main.cpp (provided to us as the assignment) this is the what we are trying to accomplish
Passed test 11...
Your match( ) return value ----> -1
Actual match( ) return value --> -1
Press the ENTER key to continue...
word = OOP data[i] =
Failed while testing the match( )
function... Failed on test 12...
Your match( ) return value ----> -1
Actual match( ) return value --> 1
Press the ENTER key to continue...
You passed 11/50 tests...
Your program is 22.00% complete!
Your program still needs some work!
Keep at it!
what the function is suppose to do is check for "oop" and if it isn't there it exits with -1, and if it is there it should return true with 1.
I guess what I'm asking is how do I make that function that it returns both -1 and 1 in the proper order?
If you would like access to the main.cpp and segement.cpp i can upload that as files somewhere because they're very long and I did not want to cram the post.
Any help is appreciated, thank you.
EDIT*
Here is the full code that we have
http://jsfiddle.net/h5aKN/
The "html" section has the segement.cpp which is what we built.
and the jscript section has the a2main.cpp which is what our professor built.
data[0] == "OOP"; is probably not what you want to do. The double = (==) tests for equality, so here you're testing if the item at the first index of data (data[0]) and the character string "OOP" are equal.
In the running of the test, you are cout'ing: word = OOP data[i] =, which means that word[i] is probably defined correctly, but data[i] is not. This goes back to the usage of the equivalence test above.
If you set initialize data correctly, (correctly meaning allocating the memory correctly, I don't know where data is instantiated), then the test would likely return -1, as it would get a non NULL pointer from the strstr() call (assuming that data is the correct type), i would be 0 on breaking, and the ternary operator would yield i-1, = -1.
So fix the initialization / assignment of the data variable
And if you're not limited to c style strings (char arrays), I'd use the std::string type and its associated methods (see the c++ string reference if you haven't already). Usually much nicer to work with
If you are passing a list of words to the function:
As the use of (strstr(&word[i],data[i])) suggests you are looking for a string inside another string. Thus you are looping over a list of strings (words).
Then this looks wrong:
int segment::match(const char word[]) {
Here you are passing one word.
Its impossable to tell what it should be, but a guess would be:
int segment::match(const char* word[]) {
// ^^^^^
But to be honest the whole thing is rather ugly C++. If you were writting C I would say fine, but if you had been writing C++ correctly the type system would have saved you from all these problems. Use std::string to represent words.

length of sub-sequence in the string

I need to implement lastSeq function,which gets as argument string str and char chr
and returns the length of last sequence of repeated chr (the sequence can be of any length)
for example:
lastSeq("abbaabbbbacd",'a') should return 1
lastSeq("abbaabbbbacd",'b') should return 4
lastSeq("abbaabbbbacd",'t') should return 0
Is there C++ function which can solve it?
This appear to be homework, so I'm just going to give you direction so that you can find the answer by yourself.
First, how would you do it yourself, without a computer to give the correct result for your samples. From those manual run, how would you generalize then in simple steps so that you can solve the problem for all different inputs.
By this point you should have a rough algorithm to solve the problem. What do you know about storage of string in C++, and the method that are available from that class? Can some one them be used to solve some of the steps of your algorithm?
Try to write a program using those function, to compile it and to run it. Do you get the expected result? If not, can you try to print intermediate state (using std::cout << "Some value: " << variable << "\n";) to try to debug it.
Once you have done all of that, and if you are still having issues, update your question with your code, and we'll be able to give you more directed help.
int lastSeq(char *str, char chr)
{
int i = strlen(str);
int l = 0;
while(--i>=0)
if(*(str + i) == chr && ++l)
break;
while(--i>=0 && chr == *(str + i) && ++l);
return l;
}