Search code examples
c++arrayscharelementerror-checking

Checking if an array is 'right' (C++)


A right array

Let's assume we have an array with an N length, made of capital letters A, B, and C. We call the array 'a right array' if between every two C letters which come one after another in the array, there are more A letters than B letters. My job is to discover whether or not a given array is 'right' and if so, I should print out "RIGHT", else I should print for how many pieces (places between to Cs) the given condition is untrue (there are more Bs than As).

Input: In the first line we enter the number of lettes in the array N (1 < N > 200). In the next line we enter the array without empty spaces in-between.

Output: Print out the answer in a single line.

Examples:

  • Input: 16 ABBCAABCACBAAACB Output: RIGHT

  • Input: 15 ABBCABCACBAAACB Output: 1

  • Input: 14 CABCABBCBAABBC Output: 3

Now, I have tried solving this problem, but the third example isn't working for me - I get an output of 2 and as given above I should get 3, other than that - it compiles perfectly fine.

    #include <iostream>

using namespace std;

int main()
{
    int N;
    cin >> N;
    char Ar[N];
    int A = 0;
    int B = 0;
    int piece = 0;
    int attempt = 0;

    for (int i = 0; i < N; i++) {
        cin >> Ar[i];
    }

    for (int i = 0;  i < N; i++) {
        if (Ar[i] == 'C') {
            for (int j = i + 1; i < N; j++) {
                if (Ar[j] == 'A') {
                    A++;
                } else if (Ar[j] == 'B') {
                    B++;
                } else if (Ar[j] == 'C') {
                    i = j;
                    break;
                }
            }
            if (A > B) {
                piece++;
                attempt++;
            } else if (A <= B) {
                attempt++;
            }
            A = 0;
            B = 0;
        }
    }


    if (piece == attempt) {
        cout << "RIGHT";
    } else {
        cout << attempt - piece;
    }

    return 0;
}

Solution

  • You have several problems, as outlined in the code comments below:

    int N;
    cin >> N;
    std::vector<char> Ar(N);
    
    for (int i = 0; i < N; i++) {
        cin >> Ar[i];
    }
    
    int piece = 0;
    int attempt = 0;
    
    for (int i = 0;  i < N - 1; i++) {
        if (Ar[i] != 'C') {
            // Skip letters until the first C
            continue;
        }
        int A = 0;
        int B = 0;
        int j = i + 1;
        for (; j < N; j++) {
            if (Ar[j] == 'A') {
                A++;
            } else if (Ar[j] == 'B') {
                B++;
            } else if (Ar[j] == 'C') {
                // We only account for blocks between Cs
                attempt++;
                if (A > B) {
                    piece++;
                }
                break;
            }
        }
        // Next piece starts at j, i will be incremented by outer loop
        i = j - 1;
    }