Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

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
...