How to check if a matrix rows contain numbers without repetition in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Class Program
	Public Shared Sub Main()
        Dim matrix As Integer(,) = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 7}}

        For i As Integer = 0 To matrix.GetLength(0) - 1
            If RowHasRepetitions(matrix, i) Then
                Console.WriteLine($"Row {i} contains repetitions.")
            Else
                Console.WriteLine($"Row {i} has unique numbers.")
            End If
        Next

        If IsMatrixValid(matrix) Then
            Console.WriteLine("All rows in the matrix contain unique numbers.")
        Else
            Console.WriteLine("Some rows in the matrix contain repeated numbers.")
        End If
    End Sub

    Private Shared Function RowHasRepetitions(ByVal matrix As Integer(,), ByVal rowIndex As Integer) As Boolean
        Dim seenNumbers As HashSet(Of Integer) = New HashSet(Of Integer)()

        For j As Integer = 0 To matrix.GetLength(1) - 1
            If Not seenNumbers.Add(matrix(rowIndex, j)) Then
                Return True
            End If
        Next

        Return False
    End Function

    Private Shared Function IsMatrixValid(ByVal matrix As Integer(,)) As Boolean
        For i As Integer = 0 To matrix.GetLength(0) - 1
            If RowHasRepetitions(matrix, i) Then
                Return False
            End If
        Next

        Return True
    End Function
End Class

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