c++ for loop counter failing - c++

Hi I am trying to count the number of zeros after a 1 has occured in a simple 1d array i dont know why the counter is always zero.
int main ()
{
int testarray[9];
testarray[0] = 0;
testarray[1] = 0;
testarray[2] = 1;
testarray[3] = 1;
testarray[4] = 0;
testarray[5] = 0;
testarray[6] = 0;
testarray[7] = 1;
testarray[8] = 1;
int counter = 0;
bool white = false;
bool prevValue =true;
bool black = true;
bool check = false;
int num = 0;
for (int i = 0; i<8; i++) {
num = testarray[i];
if (num == 1)
white = true;
else
white = false;
if((white ==true) && (prevValue == false)) {
if(i == 0) {
check = true;
i++;
}
else
check = false;
}
else {
if (check)
counter++;
}
prevValue = true;
}
cout << "Counter: "<<counter;
return 0;
}
The practical implementation involves using this for loop to detect edges. I have tried messing with the variables but to no avail. the reason that white =1, and black = 0 is because i am using this loop to solve a vision based problem. Any help would be apreciated.

because prevValue is always true : it never come to this block :
if((white ==true) && (prevValue == false)) {
if(i == 0) {
check = true;
i++;
}
else
check = false;
}
so because of this check is never assigned to 'true' so counter is not incremented

If I have understood all what you need is to find at first 1 and then to count the number of zeroes.
It can be done in one statement if to use standard algorithms.
int counter = std::count( std::find( std::begin( testarray ), std::end( testarray ), 1 ),
std::end( testarray ),
0 );

Because, with this values of the array, check is always false and it need to be true in order to allow counter variable to be incremented as you have written:
if (check)
counter++;
Also, your for loop doesn't reach the value testarray[8], you've to write
for (int i = 0; i<9; i++)
in order to include from testarray[0] to testarray[9]

Related

equal jump between numbers in two arrays

I want to compare two arrays. One of them is a subset of the other one. I want my function to return the minimum and equal gap between the numbers of the first subset array in the other array.
For example if I have
arr1 = 2,1,4,2,8,3
sub= 1,2,3
I want my function to return 1 because the mimimum gap between all this numbers are 1.
arr1 = 2,1,5,2,1,2,3
sub= 1,2,3
I want my function to return 0 because the mimimum gap between 1,2,3 in arr1 is 0
Here is the code I am trying to do: My code always return 0 can you help me understand why, and how can I solve this.
int gap(int* arr, int* sub, int sizeArr, int sizeSub)
{
int index = 0; int gap = 0; bool flag = true;
int i = -1;
for (int jump = 1; jump < sizeArr / sizeSub; jump++)
{
index = 0;
for (i = i +1; i < sizeArr; i++)
{
if (sub[index] == arr[i])
{
for (int j = i + jump, index = 1; j < sizeArr; j = j + jump, index++)
{
if (arr[j] != sub[index]) { flag = false; break; }
else if (arr[j] == sub[index] && index == sizeSub) { flag = true; break; }
}
}
if (!flag) { break; }
else { gap = jump; break; }
}
}
return gap;
}
You initially took gap equally 0 but i think more suit to not store gap
and start iterate jump from 0. And return jump immediately after you found that it is suit.
Also i think that store index in such manner as you it is bad idea, because you code return wrong answer on
int a[] = { 2,1,4,4,2,8,5,3 };
int s[] = { 1,2,3 };
I think you should declare variable as soon as possible, otherwise there will be undesirable side effects.
So you code can be rewritten as
int gap(int *arr, int *sub, int sizeArr, int sizeSub)
{
for (int jump = 0; 1 + (jump + 1) * (sizeSub - 1) <= sizeArr; jump++) {
for (int start_index = 0; start_index + (jump + 1) * (sizeSub - 1) < sizeArr; start_index++) {
bool flag = true;
for (int index = 0; index < sizeSub; ++index) {
if (arr[start_index + index * (jump + 1)] != sub[index]) {
flag = false;
break;
}
}
if (flag) {
return jump;
}
}
}
return -1; //or some value that indicate that there is no answer
}

Huffman coding c++

So I am working on Huffman coding for a project. However, my code just doesn't work. When i ran it on visual studio, it didn't give me an error. What I was trying to do is to read a file and put all of them into a string. And get the frequency for each character in that string. But I think when the file got a little bit large, it seems like my code is running in a infinite loop. Can anyone explain anything to me? By the way, I had a sorted function that I used to sort a vector of node* by their frequency.
ifstream infile;
infile.open(filename);
string q;
string line;
while (getline(infile, line))
{
q += line;
}
char y;
int count = 0;
int check = 0;
for (int i = 0; i < q.size(); i++) //if the string gets big, it seems to become an infinite loop in here
{
y = q[i];
for (int x = i - 1; x > 0; x--) //make sure not counting the same char
{
if (y == q[x])
{
check++;
}
}
if (check == 0)
{
for (int i = 0; i < q.size(); i++)
{
if (q[i] == y)
{
count++;
}
}
node*x = new node;
x->char1 = y; //my node have char
x->freq = count; //my node has frequency
list1.push_back(x);
}
count = 0;
check = 0;
}
sort(list1.begin(), list1.end(), sorter); //sort them from small to big
while (list1.size() > 1)
{
node*left = list1[0];
node*right = list1[1];
list1.erase(list1.begin(), list1.begin() + 2);
double sum = left->freq + right->freq;
node* x = new node;
x->freq = sum;
x->left = left;
x->right = right;
list1.push_back(x);
sort(list1.begin(), list1.end(), sorter);
}
list1.clear();
return true;
The following is my sort function
static struct {
bool operator()(NodeInterface* a, NodeInterface* b) {
if (a->getFrequency() == b->getFrequency()) {//if the frequencies are even,
if (b->getCharacter() == '\0') return false;
if (a->getCharacter() != '\0') {
return (int)a->getCharacter() < (int)b->getCharacter();
}
return false;
}
return a->getFrequency() < b->getFrequency();
}
} sorter;
I see two major problems.
You have a for loop inside a for loop both initializing and using int i
Change the variable name of the inner loop.
for (int i = 0; i < q.size(); i++) //if the string gets big, it seems to become an infinite loop in here
.
.
if (check == 0)
{
for (int i = 0; i < q.size(); i++) //Change this to int j for example
{
.
.
And the Sorter struct. I would rewrite it as this.
static struct {
bool operator()(NodeInterface* a, NodeInterface* b) {
if (a->getFrequency() == b->getFrequency()) {//if the frequencies are even,
if (b->getCharacter() == '\0') return false;
if (a->getCharacter() == '\0') return true;
return (int)a->getCharacter() < (int)b->getCharacter();
}
return a->getFrequency() < b->getFrequency();
}
} sorter;
A few suggestions for your for loop:
for (int i = 0; i < q.size(); i++) //if the string gets big, it seems to become an infinite loop in here
{
y = q[i];
//You can avoid this entire loop by using a structure like map
for (int x = i - 1; x > 0; x--) //make sure not counting the same char
{
if (y == q[x])
{
check++;
//break; //if you use a loop, break it once you find the character.
}
}
if (check == 0)
{
for (int j = 0; j < q.size(); j++)//Renamed variable + you can start this loop from j = i as you know there is no occurrence of y before that.
{
if (q[i] == y)
{
count++;
}
}
node*x = new node;
x->char1 = y; //my node have char
x->freq = count; //my node has frequency
list1.push_back(x);
}
count = 0;
check = 0;
}

count the ocurrences of substrings

I've a task to count the occurrences of sub string in a char String. I write this code but on certain inputs output is wrong. like string is "hassana" and sub is "as" then it outputs 2 ...some one plz help me
int CharString :: countOccurenceOf(const char* substr)
{
int count = 0;
bool find = false;
for(int i = 0; i < size1; i++)
{
if(cstr[i] == substr[0])
{
int x = i;
int c = 1;
find = true;
while ( substr[c] != '\0' && find == true && (x+1) < size1)
{
if(cstr [x+1] != substr[c])
{
find = false;
}
c++;
x++;
}
if (find == true)
{
count++;
i = i + c-1;
}
}
}
return count;
}
Got some Solution.....is that okay?
int CharString :: countOccurenceOf(const char* substr)
{
int len = 0;
if ( substr != '\0')
{
while( substr[len] != '\0')
len++;
}
int count = 0;
bool find = false;
for(int i = 0; i < size1; i++)
{
if(cstr[i] == substr[0])
{
int x = i;
int c = 1;
find = true;
while ( substr[c] != '\0' && find == true && (x+1) < size1)
{
if(cstr [x+1] != substr[c])
{
find = false;
}
c++;
x++;
}
if (find == true && c == len)
{
count++;
i = i + c-1;
}
}
}
return count;
}
The problem is that you're breaking automatically if x+1 < size1. If the first character of the substring matches the last character of the main string, then this will automatically break and "find" will still be set to true so you'll increment matches by 1. There are numerous ways to change your code to fix this problem; hopefully you can find one now that you know what the problem is.
Assuming cstr is your class internal string:
int CharString :: countOccurenceOf(const char* substr)
{
int occurrencies = 0;
unsigned char* s = cstr;
while (s) {
if (strstr(s,substr)) { occurrencies++; s+= strlen(substr); }
else s++;
}
return occurrencies;
}

Comparing to items in an Array c++

alright guys, this should be an easy one...
I have an int array and I want to see if the the numbers in the array are in succession.
For some reason when I do this (below) my array goes from int values to ascii and gets all funky and doesn't work. Any suggestions would be greatly appreciated. In this exampleit should return true.
int numArray[5] = {1,2,3,4,5};
for( int i = 0 ; i < 4 ; i++ )
{
if ( numArray[i] == numArray[i+1] - 1 )
{
continue;
}
else
{
return false;
}
}
return true;
I would write something like this, a little simpler to read.
bool issequential(const int* array, int size)
{
for (int i = 1; i < size; ++i)
if (array[i - 1] + 1 != array[i])
return false;
return true;
}

For loop just... not starting?

This is a bizarre problem. I've got a void function that performs a for loop and nothing else, but the for loop doesn't ever start, even though the function is being called. Here is the function:
void Cell::Consolidate()
{
cout << "Consolidating (outside)...\n";
for(int i = 0; i < m_Tiles.size(); ++i)
{
cout << "Consolidating (inside)...\n";
int row = m_Tiles[i]->GetRow();
int col = m_Tiles[i]->GetCol();
//Check below.
if((*m_pTileMap)[row + 1][col].pParentCell != this)
{
m_EdgeTiles.push_back(m_Tiles[i]);
m_Tiles[i]->SetColor(sf::Color(100, 100, 100));
bool newNeighbor = true;
for(int j = 0; j < m_Neighbors.size(); ++j)
{
if(m_Neighbors[j] == (*m_pTileMap)[row + 1][col].pParentCell)
{
newNeighbor = false;
break;
}
}
if(newNeighbor)
{
m_Neighbors.push_back((*m_pTileMap)[row + 1][col].pParentCell);
}
}
//Check above.
else if((*m_pTileMap)[row - 1][col].pParentCell != this)
{
m_EdgeTiles.push_back(m_Tiles[i]);
m_Tiles[i]->SetColor(sf::Color(100, 100, 100));
bool newNeighbor = true;
for(int j = 0; j < m_Neighbors.size(); ++j)
{
if(m_Neighbors[j] == (*m_pTileMap)[row - 1][col].pParentCell)
{
newNeighbor = false;
break;
}
}
if(newNeighbor)
{
m_Neighbors.push_back((*m_pTileMap)[row - 1][col].pParentCell);
}
}
//Check the right.
else if((*m_pTileMap)[row][col + 1].pParentCell != this)
{
m_EdgeTiles.push_back(m_Tiles[i]);
m_Tiles[i]->SetColor(sf::Color(100, 100, 100));
bool newNeighbor = true;
for(int j = 0; j < m_Neighbors.size(); ++j)
{
if(m_Neighbors[j] == (*m_pTileMap)[row][col + 1].pParentCell)
{
newNeighbor = false;
break;
}
}
if(newNeighbor)
{
m_Neighbors.push_back((*m_pTileMap)[row][col + 1].pParentCell);
}
}
//Check the left.
else if((*m_pTileMap)[row][col - 1].pParentCell != this)
{
m_EdgeTiles.push_back(m_Tiles[i]);
m_Tiles[i]->SetColor(sf::Color(100, 100, 100));
bool newNeighbor = true;
for(int j = 0; j < m_Neighbors.size(); ++j)
{
if(m_Neighbors[j] == (*m_pTileMap)[row][col - 1].pParentCell)
{
newNeighbor = false;
break;
}
}
if(newNeighbor)
{
m_Neighbors.push_back((*m_pTileMap)[row][col - 1].pParentCell);
}
}
}
}
When I run the program, "Consolidating (outside)...\n" gets send to cout, but "Consolidating (inside)...\n" does not. Nothing that is supposed to happen in the loop actually happens, either (for example the SetColor() calls don't do anything, nor does anything happen if I send things to cout anywhere else in the loop), so I can only assume the loop is not starting at all. Why not? What could cause this?
i < m_Tiles.size()
This loop condition gets checked on entrance to the loop, not only after each iteration. If your m_Tiles vector is empty, well, no loop for you.
Most likely, m_Tiles.size() returns a negative value or zero value.