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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to find the shortest identical consecutive subarray in an array with VB.NET

1 Answer

0 votes
Imports System

Module ShortestRunProgram

    Function shortest_identical_consecutive_subarray(arr As Integer()) As Integer()
        If arr.Length = 0 Then
            Return Array.Empty(Of Integer)()
        End If

        Dim bestStart As Integer = 0
        Dim bestLen As Integer = arr.Length

        Dim currentStart As Integer = 0
        Dim currentLen As Integer = 1

        For i As Integer = 1 To arr.Length - 1
            If arr(i) = arr(i - 1) Then
                currentLen += 1
            Else
                If currentLen < bestLen Then
                    bestLen = currentLen
                    bestStart = currentStart
                End If
                currentStart = i
                currentLen = 1
            End If
        Next

        If currentLen < bestLen Then
            bestLen = currentLen
            bestStart = currentStart
        End If

        Dim resultArr(bestLen - 1) As Integer
        Array.Copy(arr, bestStart, resultArr, 0, bestLen)

        Return resultArr
    End Function


    ' ------------------------------------------------------------
    ' MAIN PROGRAM
    ' ------------------------------------------------------------
    Sub Main()
        Dim arr As Integer() = {3, 3, 3,
                                7, 7, 7, 7, 7,
                                2, 2,
                                5, 5, 5, 5,
                                9, 9, 9, 9, 9, 9}

        Dim resultArr = shortest_identical_consecutive_subarray(arr)

        Console.Write("Array result: ")
        For Each x In resultArr
            Console.Write(x & " ")
        Next
    End Sub

End Module



' run:
'
'  Array result: 2 2 
'

 



answered 6 hours ago by avibootz

Related questions

...