How to check if a matrix rows contain numbers without repetition in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <set>

bool isRowUnique(const std::vector<int>& row) {
    std::set<int> uniqueNumbers;
    for (int num : row) {
        // If the number is already in the set, it's a repetition
        if (uniqueNumbers.find(num) != uniqueNumbers.end()) {
            return false;
        }
        uniqueNumbers.insert(num);
    }
    return true;
}

bool areMatrixRowsUnique(const std::vector<std::vector<int>>& matrix) {
    for (const auto& row : matrix) {
        if (!isRowUnique(row)) {
            return false; // If any row has repetitions, return false
        }
    }
    return true; // All rows are unique
}

int main() {
    // Matrix
    std::vector<std::vector<int>> matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 8} // This row contains a repetition
    };

    if (areMatrixRowsUnique(matrix)) {
        std::cout << "All rows contain unique numbers.\n";
    } else {
        std::cout << "Some rows contain repeated numbers.\n";
    }
}

 
 
/*
run:
 
Some rows contain repeated numbers.
 
*/

 



answered May 22, 2025 by avibootz
...