C++ Replace even number of zeros in an array with only two zeros

Viewed 383

My program should replace the group with an even number of zeros, which go in a row, with two zeros and group with an odd number of zeros replace with only one zero. If the input has no zeroes, it should be left as is. I've written following code to solve this problem.

#include <iostream> 
#include <vector> 
#include <algorithm>

using namespace std;

int main() {
    int n;
    cout << "Enter an array size:\n";
    cout << "n = ";
    cin >> n;
    vector<int> arr(n);
    vector<int> temp_arr(n);

    cout << "Enter an array:\n";
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }

    for (int i = arr.size() - 1; i >= 1; i--) {
        if (arr[i] == arr[i - 1] && arr[i] == 0){
            temp_arr.push_back(i);
        }
        else if (arr[i] != 0) {
            if (temp_arr.size() % 2 == 1) {
                arr.erase(arr.begin() + i);
                temp_arr.clear();
            }
            else if (temp_arr.size() % 2 == 0){
                arr.erase(arr.begin() + i);
                arr.insert(arr.begin() + i , 0);
                temp_arr.clear();
            }
        }
    }
    cout << "Output of the program:\n";

    for (int i = 0; i < arr.size(); i++) {
        cout << arr[i] << " ";
    }
    system("pause");
    return 0;
}

But after compilation I've got this:

The whole array was replaced with zeros

The whole array was replaced with zeros.

What did I do wrong?

1 Answers

I have altered the structure of your program (inserted a counter count_zeroes in place of auxiliary vector temp_arr), but this should work as intended:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int n;
    cout << "Enter an array size:\n";
    cout << "n = ";
    cin >> n;
    vector<int> arr(n);
    // temp_arr not used

    cout << "Enter an array:\n";
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }

    int count_zeroes = 0;
    for (int i = arr.size() - 1; i >= 0; i--) {          // index to i=0 included
        if (arr[i] == 0)
            count_zeroes++;

        if (i == 0 || arr[i] != 0) {              // corner case of arr = all zeroes included
            if (count_zeroes != 1 && count_zeroes % 2 == 1)
                arr.erase(arr.begin()+i+1, arr.begin()+i+count_zeroes);
            else if (count_zeroes != 0 && count_zeroes != 2 && count_zeroes % 2 == 0)
                arr.erase(arr.begin()+i+2, arr.begin()+i+count_zeroes);
            count_zeroes = 0;
        }
    }

    cout << "Output of the program:\n";
    for (vector<int>::size_type i = 0; i < arr.size(); i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    system("pause");

return 0;
}
Related