VB.Net Find Missing Numbers in a Sequence

I can't remember where I found the original c# version of this. I can't take credit for the logic, I merely converted it to VB.Net and used it in my app, and it works great. I did alter it a little but only to use StringCollection object since it fit into my other code nicer.

 

I had a need to find the missing numbers in a sequence. I had used SQL to try and perform this task and had found something that worked great, until I realized it didn't work when two consecutive numbers were missing. Then it would only list one of those. So instead I had used VB.Net to get me the missing numbers.

1) Create a comma delimited list of the numbers in the sequence
2) Send it to the function and return back a StringCollection object

The object returned will only have the missing numbers, if any.

 

''' <summary>
 ''' Returns the missing numbers in a sequence.   
 ''' </summary>   
 ''' <param name="strNumbers">Expects a string of comma-delimited numbers. ex: "1,2,4,6,7"</param>   
 ''' <returns></returns>   
 ''' <remarks></remarks>   
 Public Function FindMissingNumbers(ByVal strNumbers As String) As StringCollection
     Dim MissingNumbers As New StringCollection
     Dim arNumbers() As String
     arNumbers = Split(strNumbers, ",")
     arNumbers = SortNumbers(arNumbers)

     For I = 0 To UBound(arNumbers) - 1
         If CLng(arNumbers(I)) + 1 <> CLng(arNumbers(I + 1)) Then
             For J = 1 To (CLng(arNumbers(I + 1)) - CLng(arNumbers(I))) - 1
                 MissingNumbers.Add(CStr(CLng(arNumbers(I)) + J))
             Next
         End If
     Next

     Return MissingNumbers
 End Function

 ''' <summary>  
 ''' Sorts the array of numbers in value order, least to greatest.  
 ''' </summary>  
 ''' <param name="arNumbers">Send in a string() array of numbers</param>  
 ''' <returns></returns>  
 ''' <remarks></remarks>  
 Private Function SortNumbers(ByVal arNumbers() As String) As String()
     Dim tmpNumber As String
     For J = 0 To UBound(arNumbers) - 1
         For I = J + 1 To UBound(arNumbers)
             If arNumbers(I) - arNumbers(J) < 0 Then
                 tmpNumber = arNumbers(J)
                 arNumbers(J) = arNumbers(J)
                 arNumbers(I) = tmpNumber
             End If
         Next
     Next

     Return arNumbers
 End Function

 

So there you go.  The FindMissingNumbers calls the SortNumbers, notice it's Private.  You can call FindMissingNumbers and get back your Missing Numbers.

Stripping all HTML Characters using VB.Net

Upgrading my MacBook Pro 17" 200GB Hard Drive to 320GB with Boot Camp partition (using VMFusion)