VB.NET Generate unique 5 numbers between 1 and 10

2019-05-25 01:18发布

问题:

Hello I 5 unique numbers betwen 0 and 10, I'm doing as following :

Dim RandomClass As New Random()
Dim RandomNumber As Integer
For counter As Integer = 0 To 5
    RandomNumber = RandomClass.Next(0, 10)
    MsgBox(RandomNumber )
Next

Sometimes it works, I get those numbers : "1,7,4,9,3" but sometimes I get a duplicate numbers like : "5,2,3,2,7"

How can I be sure to have unique numbers each time?

Thank you.

回答1:

Use HashSet(Of Integer) to remember numbers that have already been printed out:

Dim RandomClass As New Random()
Dim RememberSet As New HashSet(Of Integer)

Dim RandomNumber As Integer

While RememberSet.Count < 5
    RandomNumber = RandomClass.Next(0, 10)
    If RememberSet.Add(RandomNumber) Then
        MsgBox(RandomNumber)
    End If
End While


回答2:

Just for fun, a different approach, make a list of integers from 0 to 10, use the random generator to get an index inside this list, print that number and remove from the list. Keep the generation of the random numbers inside the limits

Dim numbers = Enumerable.Range(0, 11).ToList()
Dim RandomClass As New Random()
Dim RandomIndex As Integer
For counter As Integer = 1 To 5
    RandomIndex = RandomClass.Next(0, numbers.Count)
    MsgBox(numbers(RandomIndex))
    numbers.RemoveAt(RandomIndex)
Next


回答3:

I would suggest adding a seed so that random numbers are not repeated.

Dim RandomClass As New Random(DateTime.Now.Ticks)
Dim RememberSet As New HashSet(Of Integer)

Dim RandomNumber As Integer

While RememberSet.Count < 5
    RandomNumber = RandomClass.Next(0, 10)
    If RememberSet.Add(RandomNumber) Then
        MsgBox(RandomNumber)
    End If
End While


回答4:

try following:

 Sub Main()

    Dim a As String() = New String(2) {}
    Dim b As String
    Dim c As Integer = 0
    Dim d As String = " "
    Do
        Console.Clear()
        Console.Write("Enter your name:")
        a(c) = Console.ReadLine()
        c += 1

    Loop Until c = 3
    For Each d In a
        Console.Write(" " & d)
    Next
    Console.ReadLine()


标签: vb.net random