Fill an Integer Array with Mutually Exclusive Random Integers

This function will fill an integer array with mutually exclusive numbers.

VB.NET

''' <summary>
''' Fills an integer array with random, mutually exclusive integers.
''' </summary>
''' <param name="intArray">The integer array to use.</param>
''' <returns>The random, mutually exclusing integer array.</returns>
''' <remarks></remarks>
Public Function fillIntArrRndMutExclInts(ByRef intArray As Integer()) As Integer()
    Dim intResult(intArray.Length - 1) As Integer
    Dim rndInstance As New Random()
    ' Loop through all elements in the integer array.
    For i As Integer = 0 To intResult.Length - 1
        ' Create a GoTo point when it creats a random number
        ' that isn't mutually exclusive.
GoAgain:
        ' Give the array number a value so we can check it
        intResult(i) = rndInstance.Next(0, intResult.Length)

        ' Check if there are any other arrays with the
        ' newly created random value.
        For j As Integer = 0 To intResult.Length - 1
            ' Ignore the array that we just assigned a value to.
            If j = i Then Continue For

            ' If not mutually exclusive, this will be true.
            If intResult(i) = intResult(j) Then GoTo GoAgain
        Next

        ' A number has been born! :D
    Next

    Return intResult
End Function

' Example usage:
Dim intArray(1000) As Integer ' Our array of integers.
intArray = fillIntArrRndMutExclInts(intArray)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License