How to check if any row of a matrix contains all 'A's?

Viewed 187

I've been trying to do this, but the problem is that there's always something wrong or missing with the final result. I have a lot of if statements and I wanted to see if it is possible to reduce it by using a for loop.

char matrix[3][3] = {
    {'A','A','A'},{'B','A','B'},{'C','A','C'}
};

if (matrix[0][0] == 'A' && matrix[0][1] == 'A' && matrix[0][2] == 'A') {
            cout << "Found!" << endl;
        }

There are a lot more if statements and I didn't put it here because it's the same thing just different index.

I tried to do a for loop like this,

for (int i = 0; i < matrix[0][2]; i++) {
            if (matrix[0][0] == matrix[0][1] && matrix[0][0] == matrix[0][2])
                cout << "Found!" << endl;
            break;
        }

This looks more organized compared to almost 20 lines of if statements, but it still missing some parts. For example in the array [0][1] and [1][1] and [2][1] all have the character 'A'. How can implement this into the for loop to print out the message when the same character appears in the same line vertically or horizontally.

1 Answers

You can use standard algorithms to express this conveniently:

if (std::any_of(std::begin(matrix), std::end(matrix), 
                [](auto const & row) {
                    return std::all_of(std::begin(row), std::end(row), 
                                       [](char c) {
                                           return c == 'A';
                                       });
                }))
{
    std::cout << "Found";
}

From C++20, this becomes a little easier to read and write:

namespace rs = std::ranges;
if (rs::any_of(matrix, [](auto const & row) {
        return rs::all_of(row, [](char c) {
            return c == 'A';
        });
    }))
{
    std::cout << "Found";
}

Here's a demo

Related