The task is to make a program that converts the incoming array, replacing two consecutive zeroes (00) by 1. For example, 10010 by 1110

#include <iostream> #include <stdlib.h> using namespace std; int main() { int in[8], out[8], i; cout << "In:" << endl; //Входящий поток for (i=0;i<8;i++) //Ввод потока { cout << "In[" << i << "]="; cin >> in[i]; if (in[i]!=0 && in[i]!= 1) { cout << "Incorrect In. Only 0 and 1 permitted." << endl; exit(0); } } cout << endl; for (i=0; i<8; i++) cout << in[i]; cout << endl << endl << "Out:" << endl; for (i=0; i<8; i++) { int j=0; if(in[i]==1) {out[j]=1; j++;} if(in[i]==0) { if (in[i+1]==1) { out[j]=0; j++; } if (in[i+1]==0) { out[j]=1; j++; i++; //Где-то тут жесткий косяк } } } cout << endl; for (i=0; i<j; i++) cout << out[i]; cout << endl; return 0; } 

The output ignores my i ++ in the line with the comment about the joint, does not look very Not really

The question is obvious , why is i ++ ignored and how to make it work?

Thank you in advance.

  • and if 000 then what should be? - pavel
  • 10, processing goes from left to right. - Igelkotten
  • Well, you will have 110, do you need to understand or just a code worker? - pavel
  • Understand, because I sincerely do not realize where the joint is. I only get acquainted with the pluses. - Igelkotten
  • The given fragment should not be compiled at all, since j is used outside its scope. And there should also be a warning that i is twice announced - German Borisov

1 answer 1

First we format

 if(in[i]==1){ out[j]=1; j++; } else { if (in[i+1]==1){ out[j]=0; j++; } else { out[j]=1; j++; i++; } 

If there was a unit, it will remain, ok. If we have 0, then we look at the next character - this is no longer the case, we need to know the number of previous 0's still ... Need to change the logic. We don’t mind the memory, so we set up a variable.

 int countZero = 0; ... else { countZero++; if (countZero&1) ;//ничего не нужно делать else //к ответу добавить 1 

Now it needs to be properly reset.

 if(in[i]==1){ countZero = 0; 

But we play odd 0. Now everything is assembled. The bonus can be immediately displayed without an array and all elements are read exactly 1 time.

 bool countZero = 0; for (int i =0; i<8;i++){ if(a[i]){ if (countZero) cout << 0; countZero = 0; cout << 1; } else { countZero ^=1; if (!countZero) cout << 1; } } if (countZero) cout << 0; cout << endl; 

Example: http://ideone.com/HJmWrN