How to find repeated patterns of numbers in the rows of a matrix with VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Class PatternFinder
    Private Shared Sub FindRepeatingPatterns(ByVal matrix As List(Of List(Of Integer)), ByVal patternSize As Integer)
        Dim patternMap As Dictionary(Of String, HashSet(Of Integer)) = New Dictionary(Of String, HashSet(Of Integer))()

        For row As Integer = 0 To matrix.Count - 1
            For col As Integer = 0 To matrix(row).Count - patternSize
                Dim pattern As String = String.Join("-", matrix(row).GetRange(col, patternSize))

                If Not patternMap.ContainsKey(pattern) Then
                    patternMap(pattern) = New HashSet(Of Integer)()
                End If

                patternMap(pattern).Add(row)
            Next
        Next

        Console.WriteLine("Repeated Patterns Found:")

        For Each entry In patternMap
            If entry.Value.Count > 1 Then
                Console.Write(entry.Key & " appears " & entry.Value.Count & " times in rows: ")

                For Each row As Integer In entry.Value
                    Console.Write(row & " ")
                Next

                Console.WriteLine()
            End If
        Next
    End Sub

	Public Shared Sub Main()
        Dim matrix As List(Of List(Of Integer)) = New List(Of List(Of Integer)) From {
            New List(Of Integer) From {
                1, 2, 3, 8, 9, 7, 4, 9, 6
            },
            New List(Of Integer) From {
                1, 3, 2, 7, 8, 9, 4, 5, 6
            },
            New List(Of Integer) From {
                1, 2, 3, 8, 6, 1, 4, 9, 8
            },
            New List(Of Integer) From {
                1, 2, 3, 0, 8, 8, 4, 5, 9
            },
            New List(Of Integer) From {
                1, 2, 3, 4, 5, 6, 7, 8, 9
            },
            New List(Of Integer) From {
                1, 2, 3, 7, 0, 9, 4, 5, 7
            },
            New List(Of Integer) From {
                1, 3, 2, 4, 5, 6, 7, 8, 9
            }
        }
        Dim patternSize As Integer = 3

        FindRepeatingPatterns(matrix, patternSize)
    End Sub
End Class

 
' run:
'
' Repeated Patterns Found:
' 1-2-3 appears 5 times in rows: 0 2 3 4 5 
' 2-3-8 appears 2 times in rows: 0 2 
' 1-3-2 appears 2 times in rows: 1 6 
' 7-8-9 appears 3 times in rows: 1 4 6 
' 9-4-5 appears 2 times in rows: 1 5 
' 4-5-6 appears 3 times in rows: 1 4 6 
' 5-6-7 appears 2 times in rows: 4 6 
' 6-7-8 appears 2 times in rows: 4 6 
'

 



answered May 25 by avibootz
...