Home > other >  While list with integer is not contains integer generate random number
While list with integer is not contains integer generate random number

Time:12-29

how do i make this work, as while the random numbers x exists in list to be generated until number x does not exist in list. so generate until it finds the number that does not exist in the list.

            Dim listwithdeck As New List(Of Integer)
            While listwithdeck.Contains(num) = False
                MessageBox.Show(num)
                num = rnd.Next(2, 15)
                listwithdeck.Add(num)
            End While

CodePudding user response:

This code will run until a duplicate random is produced.

Private rnd As New Random

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim num As Integer
    Dim listwithdeck As New List(Of Integer)
    Do
        num = rnd.Next(2, 15)
        If listwithdeck.Contains(num) Then
            Exit Do
        Else
            listwithdeck.Add(num)
        End If
    Loop
    For Each i In listwithdeck
        Debug.Print(i.ToString)
    Next
End Sub

CodePudding user response:

If you are looking for a random list between two numbers try this.
For 2 and 15 the call would be RandList(2,16).

Private Shared PRNG As New Random
''' <summary>
''' returns a list of random integers between minIncl and maxExcl -1
''' </summary>
''' <param name="minIncl">minimum number</param>
''' <param name="maxExcl">maximum number, not included</param>
''' <returns></returns>
''' <remarks></remarks>
Private Function RandList(minIncl As Integer, maxExcl As Integer) As List(Of Integer)
    Dim rv As IEnumerable(Of Integer)
    rv = Enumerable.Range(minIncl, maxExcl - minIncl).OrderBy(Function() PRNG.Next)
    Return rv.ToList
End Function
  • Related