VB.NET生成1到10之间的唯一5个数字

时间:2013-08-17 21:52:33

标签: vb.net random

你好我在0和10之间的5个唯一数字,我正在做如下:

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

有时它有效,我得到那些数字:“1,7,4,9,3” 但有时我得到一个重复的数字,如:“5,2,3,2,7”

我怎样才能确保每次都有唯一的数字?

谢谢。

4 个答案:

答案 0 :(得分:5)

使用HashSet(Of Integer) 记住已打印过的数字:

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

答案 1 :(得分:2)

只是为了好玩,一种不同的方法,制作一个从0到10的整数列表,使用随机生成器获取此列表中的索引,打印该数字并从列表中删除。将随机数的生成保持在限制范围内

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

答案 2 :(得分:0)

我建议添加种子,以便不重复随机数。

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

答案 3 :(得分:0)

尝试以下:

 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()