How to generate a random integer from a range [0, N] that is not in a unique integer list with VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Module RandomExcludingModule

    Function RandomExcluding(N As Integer, excluded As List(Of Integer)) As Integer
        If excluded.Count > N + 1 Then
            Return -1 ' All numbers are excluded
        End If

        Dim rand As New Random()
        Dim num As Integer

        Do
            num = rand.Next(0, N + 1) ' Inclusive range [0, N]
        Loop While excluded.Contains(num)

        Return num
    End Function

    Sub Main()
        Dim excluded As New List(Of Integer) From {2, 5, 7}
        Dim N As Integer = 14

        Dim result As Integer = RandomExcluding(N, excluded)
        Console.WriteLine(result)
    End Sub

End Module


' run:
'
' 10
'

 



answered 22 hours ago by avibootz

Related questions

...