g++ error: stray '\177' in program - c++

I was trying to code for following program
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9] insert and merge [2,5] would result in [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] would result in [1,2],[3,10],[12,16].
This is the relevant part of my program
here. I want to erase the few positions from the vector
then I am getting the following error
error: stray '\177' in program
intervals.erase(intervals.begin()+(p+1),intervals.begin()+(q+1));
vector<Interval> Solution::insert(vector<Interval> &intervals, Interval newInterval) {
int n = intervals.size();
int p=-1,q=-1,a,b;
for(int i=0;i<n;++i){
if(intervals[i].start <= newInterval.start <= intervals[i+1].end)
p = i;
else if(intervals[i].end < newInterval.start < intervals[i+1].start)
a = i;
if(intervals[i].start <= newInterval.end <= intervals[i+1].end)
q = i;
else if(intervals[i].end < newInterval.end < intervals[i+1].start)
b = i;
}
int x,z;
if(p != -1 && q != -1)
x = q-p;
if(x > 0){
z=intervals[q].end;
intervals.erase(intervals.begin()+(p+1),intervals.begin()+(q+1));
intervals[p].end = z;
}
return vector
}

Did you copy that code from a website?
I managed to reproduce your result with this snippet:
const char* msg = "You can't copy this";
When copied and put on coliru here you'll get the same error code.
What I used for the above snippet in HTML code was:
<code>const char* msg = </code><code>"You can't copy this";
</code>
Note the  character I put in there.
To fix that, you can use a decent editor like Notepad++ that will make the stray characters visible:

Related

iterating vector of strings C++

The code is to read instructions from text file and print out graphic patterns. One is my function is not working properly. The function is to read the vectors of strings I've got from the file into structs.
Below is my output, and my second, third, and sixth graphs are wrong. It seems like the 2nd and 3rd vectors are not putting the correct row and column numbers; and the last one skipped "e" in the alphabetical order.
I tried to debug many times and still can't find the problem.
typedef struct Pattern{
int rowNum;
int colNum;
char token;
bool isTriangular;
bool isOuter;
}Pattern;
void CommandProcessing(vector<string>& , Pattern& );
int main()
{
for (int i = 0; i < command.size(); i++)
{
Pattern characters;
CommandProcessing(command[i], characters);
}
system("pause");
return 0;
}
void CommandProcessing(vector<string>& c1, Pattern& a1)
{
reverse(c1.begin(), c1.end());
string str=" ";
for (int j = 0; j < c1.size(); j++)
{
bool foundAlpha = find(c1.begin(), c1.end(), "alphabetical") != c1.end();
bool foundAll = find(c1.begin(), c1.end(), "all") != c1.end();
a1.isTriangular = find(c1.begin(), c1.end(), "triangular") != c1.end() ? true : false;
a1.isOuter = find(c1.begin(), c1.end(), "outer") != c1.end() ? true : false;
if (foundAlpha ==false && foundAll == false){
a1.token = '*';
}
//if (c1[0] == "go"){
else if (c1[j] == "rows"){
str = c1[++j];
a1.rowNum = atoi(str.c_str());
j--;
}
else if (c1[j] == "columns"){
str = c1[++j];
a1.colNum = atoi(str.c_str());
j--;
}
else if (c1[j] == "alphabetical")
a1.token = 0;
else if (c1[j] == "all"){
str = c1[--j];
a1.token = *str.c_str();
j++;
}
}
}
Before debugging (or posting) your code, you should try to make it cleaner. It contains many strange / unnecessary parts, making your code harder to understand (and resulting in the buggy behaviour you just described).
For example, you have an if in the beginning:
if (foundAlpha ==false && foundAll == false){
If there is no alpha and all command, this will be always true, for the entire length of your loop, and the other commands are all placed in else if statements. They won't be executed.
Because of this, in your second and third example, no commands will be read, except the isTriangular and isOuter flags.
Instead of a mixed structure like this, consider the following changes:
add a default constructor to your Pattern struct, initializing its members. For example if you initialize token to *, you can remove that if, and even the two bool variables required for it.
Do the parsing in one way, consistently - the easiest would be moving your triangular and outer bool to the same if structure as the others. (or if you really want to keep this find lookup, move them before the for loop - you only have to set them once!)
Do not modify your loop variable ever, it's an error magnet! Okay, there are some rare exceptions for this rule, but this is not one of them.
Instead of str = c1[++j];, and decrementing later, you could just write str = c1[j+1]
Also, are you sure you need that reverse? That makes your relative +/-1 indexing unclear. For example, the c1[j+1 is j-1 in the original command string.
About the last one: that's probably a bug in your outer printing code, which you didn't post.

Why is this code showing some junk type of value when it shows the correct value on my machine?

I am trying to write a code for implementing Djisktra's Algorithm... And having some problem with it
The link to the code is Ideone...
When the same code is run over my PC the output comes out to be
0 4 12 19 21 11 9 8 14
And the output one ideone is
0 4 12 19 21 11 9 8 16777230
See the difference in the last element 14...I am pretty clueless about it... Is there some error in my code ? Or it is happening due to some other reason over online compilers or am I doing something stupid?
Potential Error here
int find(int start)
{
int low=INT_MAX,idx=-1,i;
for(i=0;i<V;i++)
if( !(Left[i]) && low>=Distances[i])
{
idx=i;
low=Distances[i];
}
return idx;
}
while(start != -1)
{
for(i = 0; i < V; i++)
if(graph[start][i] && Distances[start] + graph[start][i] < Distances[i])
Distances[i] = graph[start][i] + Distances[start];
start = find(start);
Left[start] = true;
}
I have tried finding the reason.. The distance at V-1 is 14 at some point(I tried printing it) but it is not updated Later(I tried printing it whenever the distance of V-1 was updated) But it seems it was not updated later on!!
I am a beginner please do tell me where am I going wrong
NOTE: (Graph is a 2D adjacency matrix) Distances is an array of int type and Left is of bool type )
You have undefined behavior in the while loop in the code on ideone which doesn't match the code you've posted here. This is why others admonish you for not providing a minimal example. When find returns -1, Left[start] = true accesses before the start of the array. Since it is undefined behavior, it could do anything, including work correctly on your PC and fail on ideone. To fix, since you have a Left[start] = true before the while loop, remove it, and move it to the top of the while:
while(start != -1)
{
Left[start] = true;
for(i = 0; i < V; i++)
if(graph[start][i] && Distances[start] + graph[start][i] < Distances[i])
Distances[i] = graph[start][i] + Distances[start];
start = find(start);
}
Corrected code on ideone (also removed some unused variables).

Vector changes value unexpected

I am making a little game (just console) and my vectors don't act like I think they have to. One Value of the vector just changes and I don't know why. The Code shown below is part where this bug come from, I have deleted the rest of the code where these 2 vectors show up and the bug still appears and I DONT KNOW WHY!!
This part of the code is responsible for letting the Enemy spread to a random direction.
/**in this part the first value of the 2 vectors are created
(only once, I've tested it)**/
if(moves == 0){
int randomNum1 = (rand() % HEIGHT)+1;
int randomNum2 = (rand() % WIDTH)+1;
_EnemysY.push_back(randomNum1);
_EnemysX.push_back(randomNum2);
}
/**_Enemy vectors have normal values. For instance: _EnemysX[0]
is 23 and _EnemysY[0] is 12**/
/**In this part, the Enemy spreads in a random direction**/
if (moves > 3){
//save Enemys at the border here (those who can move)
std::vector<int> topX;
std::vector<int> topY;
std::vector<int> botX;
std::vector<int> botY;
std::vector<int> rigX;
std::vector<int> rigY;
std::vector<int> lefX;
std::vector<int> lefY;
/**here, I wanna save all Fields of the Enemy where it can spread to:**/
for (Uint it = 0; it < _EnemysY.size(); it++){
/**_EnemysY is still normal, but _EnemysX is like: 86BF163E0**/
if (_map[_EnemysY[it]-1][_EnemysX[it]] == _Grenade || _map[_EnemysY[it]-1][_EnemysX[it]] == _Field){
topY.push_back(_EnemysY[it]);
topX.push_back(_EnemysX[it]);
}
if (_map[_EnemysY[it]+1][_EnemysX[it]] == _Grenade || _map[_EnemysY[it]+1][_EnemysX[it]] == _Field){
botY.push_back(_EnemysY[it]);
botX.push_back(_EnemysX[it]);
}
if (_map[_EnemysY[it]][_EnemysX[it]-1] == _Grenade || _map[_EnemysY[it]][_EnemysX[it]-1] == _Field){
lefX.push_back(_EnemysX[it]);
lefY.push_back(_EnemysY[it]);
}
if (_map[_EnemysY[it]][_EnemysX[it]+1] == _Grenade || _map[_EnemysY[it]][_EnemysX[it]+1] == _Field){
rigX.push_back(_EnemysX[it]);
rigY.push_back(_EnemysY[it]);
}
}
/**and here is a random direction created and the programm
chooses which Field it will spread to: **/
for (;;){
int ranDir = (rand() % 4)+1;
if (ranDir == 1 && !topY.empty()){
int temp = (rand() % topY.size())+1;
_EnemysY.push_back(topY[temp]);
_EnemysX.push_back(topX[temp]);
return true;
}
if (ranDir == 2 && !botY.empty()){
int temp = (rand() % botY.size())+1;
_EnemysY.push_back(botY[temp]);
_EnemysX.push_back(botX[temp]);
return true;
}
if (ranDir == 3 && !lefY.empty()){
int temp = (rand() % lefY.size())+1;
_EnemysY.push_back(lefY[temp]);
_EnemysX.push_back(lefX[temp]);
return true;
}
if (ranDir == 4 && !rigY.empty()){
int temp = (rand() % rigY.size())+1;
_EnemysY.push_back(rigY[temp]);
_EnemysX.push_back(rigX[temp]);
return true;
}
}
}
First off, why not have a struct describing the "enemy", including its position (via two fields X and Y)? It would improve the code a bit and avoid the need for two vectors that are meaningless if separated.
On topic:
int temp = (rand() % rigY.size())+1;
_EnemysY.push_back(rigY[temp]);
rand() % rigY.size() will give you a number in the interval [0, rigY.size() ). You then add 1 to both sides so temp would be in the interval [1, rigY.size() ].
But rigY[rigY.size()] is not a valid element in the vector...
First of all: thank you Andrei and PaulMcKenzie for your time, your answers didn't solve the problem, but they were still usefull. :)
Now to the answer of the problem:
Alright! I'm a complete douchebag! Because what I didn't print in the code above, was my std::cout s for my variables and I accidentally wrote: "std::cout << ... << std:cout << ... std::endl" and for some reason the second "std::cout" caused a bug, where it printed out an ridiculously high number. So my code in general (without the cout s) works fine, but I still changed some things which you said.

bus error caused by print statement

Ok so I have simple function that returns the highest non-pair card from a 5 card poker hand. But he problem I'm having is wierd. There is this random bus error that occurs randomly, and I don't know for what reason. I thought it was the print statements I was using but now I'm not sure. I know it looks a mess, but if you look at the line below where I print the words "test print", can someone tell me why immediately after this line theres a bus error and it doesn't get to the second "test print" statement. Could I have run out of memory for my program??? That probably makes no sense, but I can't really think of anything else (please exclude the slightly confusing code):
int Hand::highestNonPair(int *face_array_exclude, int size)
{
int highest = 0;
int contains_excludable = 0;
int i = 0;
if(this->hasAnother(i) == false)
highest = cards[i]->getFace();
for(i= 0;i<cards.size();i++)
{
if((cards[i+1]->getFace() > cards[i]->getFace()) &&
(this->hasAnother(i) == false)){
if(size>0){
for(int c = 0;c<size;c++){
if(cards[i]->getFace() == face_array_exclude[c])
contains_excludable = 1;
}
}
if(!contains_excludable)
highest = cards[i+1]->getFace();
cout<<\nTEST PRINT"<<endl;
contains_excludable = 0;
cout<<\nTEST PRINT"<<endl;
}
}
return highest;
}
The bit can case problems:
if((cards[i+1]->getFace() > cards[i]->getFace()) &&
As the highest value of i could be cards.size() - 1. This would mean that cards[i+1 will be an invalid entry.
Change the loop:
for(i= 0;i<cards.size();i++)
to
for(i= 0;i<cards.size() - 1;i++)
Perhaps

Need to find a logic error in a card shuffling method

I'm trying to write a method that takes an array of integers (0-51, in that order), cuts it into two separate arrays (A and B in the below function by using the cut method, which I know for sure works) and then re-fuses the two arrays together by randomly selecting 0, 1 or 2 cards from the BOTTOM of either A or B and then adding them to the deck.
(ps- by "array" I mean linked list, I just said array because I thought it would be conceptually easier)
This is my code so far, it works, but there's a definite bias when it comes to where the cards land. Can anybody spot my logic error?
[code]
void Deck::shuffle(){
IntList *A = new IntList();
IntList *B = new IntList();
cut(A, B);
IntListNode *aMarker = new IntListNode;
aMarker = A->getSentinel()->next;
//cout<< A->getSentinel()->prev->prev->data <<'\n'<<'\n';
IntListNode *bMarker = new IntListNode;
bMarker = B->getSentinel()->next;
//cout<< B->getSentinel()->prev->data;
deckList.clear();
srand(time(NULL));
int randNum = 0, numCards = 0, totalNumCards = 0;
bool selector = true, aisDone = false, bisDone = false;
while(totalNumCards < 52){
randNum = rand() % 3;
if(randNum == 0){
selector = !selector;
continue;
}
numCards = randNum;
if(!aisDone && !bisDone){
if(selector){
for(int i = 0; i < numCards; i++){
deckList.push_back(aMarker->data);
aMarker = (aMarker->next);
if(aMarker == A->getSentinel()){
aisDone = true;
break;
}
}
selector = false;
}else{
for(int i = 0; i < numCards; i++){
deckList.push_back(bMarker->data);
bMarker = (bMarker->next);
if(bMarker == B->getSentinel()){
bisDone = true;
break;
}
}
selector = true;
}
}
if(aisDone && !bisDone){
for(int i = 0; i < (52 - totalNumCards); i++){
deckList.push_back(bMarker->data);
bMarker = (bMarker->next);
if(bMarker == B->getSentinel()){
bisDone = true;
break;
}
}
//return;
}
if(bisDone && !aisDone){
for(int i = 0; i < (52 - totalNumCards); i++){
deckList.push_back(aMarker->data);
aMarker = (aMarker->next);
if(aMarker == A->getSentinel()){
aisDone = true;
break;
}
}
//return;
}
totalNumCards += numCards;
}
int tempSum = 0;
IntListNode *tempNode = deckList.head();
for(int j = 0; j < 52; j++){
//cout<< (tempNode->data) << '\n';
tempSum += (tempNode->data);
tempNode = (tempNode ->next);
}
if(tempSum != 1326)
system("PAUSE");
return;
}
[/code]
What about just using std::random_shuffle? Yeah, it won't work for linked list, but you can change it to vector :)
If your instructor would have the moral to teach you programming the way it should be done then they'd encourage you to solve the problem like so, with four lines of code:
#include<algorithm>
#include<vector>
// ...
std::vector<int> cards; // fill it in ...
std::random_shuffle(cards.begin(), cards.end());
Using the standard library is the right way of doing things. Writing code on your own when you can solve the problem with the standard library is the wrong way of doing things. Your instructor doesn't teach you right. If they want to get a point across (say, have you practice using pointers) then they should be more attentive in selecting the exercise they give you.
That speech given, here is a solution worse than the above but better than your instructor's:
52 times do the following:
Choose two random none-equal integers in the range [0,52).
Swap the values in the array corresponding to these positions.
For most random number generators, the low bits are the least random ones. So your line
randNum = rand() % 3;
should be modified to get its value more from the high- to middle-order bits from rand.
Your expectations may be off. I notice that you swap the selector if your random value is 0. Coupled with the relative non-randomness of randNum, this may be your problem. Perhaps you need to make things less random to make them appear more random, such as swapping the selector every time through the loop, and always taking 1 or more cards from the selected deck.
Comments:
srand(time(NULL));
This should only be called once during an applications run. This it is usally best to call it in main() as you start.
int randNum = 0, numCards = 0, totalNumCards = 0;
bool selector = true, aisDone = false, bisDone = false;
One identifier per line. Every coding standard written has this rule. It also prevents some subtle errors that can creep in when using pointers. Get used to it.
randNum = rand() % 3;
The bottom bits of rand are the lest random.
rand Num = rand() / (MAX_RAND / 3.0);
Question:
if(!aisDone && !bisDone)
{
This can execute
and set one of the above to isDone
Example:
Exit state aisDone == false bsiDone == false // OK
Exit state aisDone == true bsiDone == false // Will run below
Exit state aisDone == false bsiDone == ture // Will run below
}
if(aisDone && !bisDone)
{
Is this allowed to run if the first block above is run?
}
if(bisDone && !aisDone)
{
Is this allowed to run if the first block above is run?
}
The rest is too complicated and I don't understand.
I can think of simpler techniques to get a good shuffle of a deck of cards:
for(loop = 0 .. 51)
{
rand = rand(51 - loop);
swap(loop, loop+rand);
}
The above simulates picking a card at random from the deck A and putting it on the top of deck B (deck B initially being empty). When the loop completes B is now A (as it was done in place).
Thus each card (from A) has the same probability of being placed at any position in B.