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

1 Answer

0 votes
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        int[,] matrix = {
            { 1, 2, 3 },
            { 4, 5, 6 },
            { 7, 8, 7 } // This row contains a repetition
        };

        for (int i = 0; i < matrix.GetLength(0); i++) {
            if (RowHasRepetitions(matrix, i)) {
                Console.WriteLine($"Row {i} contains repetitions.");
            }
            else {
                Console.WriteLine($"Row {i} has unique numbers.");
            }
        }

        if (IsMatrixValid(matrix)) {
            Console.WriteLine("All rows in the matrix contain unique numbers.");
        }
        else {
            Console.WriteLine("Some rows in the matrix contain repeated numbers.");
        }
    }

    // Checks if a specific row has repeated numbers
    static bool RowHasRepetitions(int[,] matrix, int rowIndex) {
        HashSet<int> seenNumbers = new HashSet<int>();

        for (int j = 0; j < matrix.GetLength(1); j++) {
            if (!seenNumbers.Add(matrix[rowIndex, j])) {
                return true; // If Add() returns false, the number is already in the set
            }
        }

        return false; // No repetitions found
    }

    // Checks if all rows in the matrix have unique numbers
    static bool IsMatrixValid(int[,] matrix) {
        for (int i = 0; i < matrix.GetLength(0); i++) {
            if (RowHasRepetitions(matrix, i)) {
                return false; // If any row contains repetitions, return false
            }
        }
        
        return true; // All rows are unique
    }
}



/*
run:

Row 0 has unique numbers.
Row 1 has unique numbers.
Row 2 contains repetitions.
Some rows in the matrix contain repeated numbers.

*/

 



answered May 23, 2025 by avibootz
...