2

我有一些 VB 代码给我一个随机数,1 介于 20 (X) 之间。但是,在 20 次尝试中,我会得到两次相同的数字。我怎样才能得到一个随机数序列而不重复它们?如果我单击一个按钮 20 次,我基本上希望 1-20 以随机顺序显示。

    Randomize()
    ' Gen random value

    value = CInt(Int((X.Count * Rnd())))

    If value = OldValue Then
        Do While value = OldValue
            value = CInt(Int((X.Count * Rnd())))    
        Loop
    End If
4

4 回答 4

1

For 1 to 20, use a data structure like a LinkedList which holds numbers 1 to 20. Choose an index from 1 to 20 at random, take the number at that index, then pop out the number in that location of the LinkedList. Each successive iteration will choose an index from 1 to 19, pop, then 1 to 18, pop, etc. until you are left with index 1 to 1 and the last item is the last random number. Sorry for no code but you should get it.

于 2013-03-28T04:14:10.520 回答
1

概念是,您必须将add其添加generated random number到 alist中,并且在将其添加到 之前list,请确保anew number不在contains其中。试试这个代码,

        Dim xGenerator As System.Random = New System.Random()
        Dim xTemp As Integer = 0
        Dim xRndNo As New List(Of Integer)

        While Not xRndNo.Count = 20

            xTemp = xGenerator.Next(1, 21)

            If xRndNo.Contains(xTemp) Then
                Continue While
            Else
                xRndNo.Add(xTemp)
            End If

        End While

[注:测试与IDE]

于 2013-03-28T05:48:05.420 回答
0

为此,您需要存储所有先前生成的数字,而不仅仅是一个,就像您在 OldValue 命名变量中所做的那样。因此,将所有先前生成的数字存储在某处(列表)。并将新生成的数字与列表中的所有数字进行比较,在你的while循环中,并继续生成数字,而数字不等于列表中的任何一个。

于 2013-03-28T04:01:35.513 回答
0

将数字添加到列表中,然后以随机顺序选择它们,在选择它们时删除它们。

Dim prng As New Random
Dim randno As New List(Of Integer)

Private Sub Button1_Click(sender As Object, _
                          e As EventArgs) Handles Button1.Click
    If randno.Count = 0 Then
        Debug.WriteLine("new")
        randno = Enumerable.Range(1, 20).ToList 'add 1 to 20 to list
    End If
    Dim idx As Integer = prng.Next(0, randno.Count) 'pick a number
    Debug.WriteLine(randno(idx)) 'show it
    randno.RemoveAt(idx) 'remove it
End Sub
于 2013-03-28T15:12:12.327 回答