随机数但不要重复

时间:2009-08-02 04:29:21

标签: vb.net shuffle

我想生成一个小于50的随机数,但是一旦生成了这个数字,我希望它不能再生成。

感谢您的帮助!

4 个答案:

答案 0 :(得分:13)

请参阅:Fisher–Yates shuffle

public static void shuffle (int[] array) 
{
    Random rng = new Random();       // i.e., java.util.Random.
    int n = array.length;            // The number of items left to shuffle (loop invariant).
    while (n > 1) 
    {
        n--;                         // n is now the last pertinent index
        int k = rng.nextInt(n + 1);  // 0 <= k <= n.
        int tmp = array[k];
        array[k] = array[n];
        array[n] = tmp;
    }
}

答案 1 :(得分:9)

将数字1-49放入可排序的集合中,然后按随机顺序对其进行排序;根据需要从集合中弹出每一个。

答案 2 :(得分:5)

看到问题被标记为VB / VB.Net ......这是Mitch回答的VB实现。

Public Class Utils

   Public Shared Sub ShuffleArray(ByVal items() As Integer)

      Dim ptr As Integer
      Dim alt As Integer
      Dim tmp As Integer
      Dim rnd As New Random()

      ptr = items.Length

      Do While ptr > 1
         ptr -= 1
         alt = rnd.Next(ptr - 1)
         tmp = items(alt)
         items(alt) = items(ptr)
         items(ptr) = tmp
      Loop

   End Sub

End Class

答案 3 :(得分:0)

下面的代码生成字母数字字符串,其长度作为参数传递。

Public Shared Function GetRandomAlphaNumericString(ByVal intStringLength As Integer) As String

Dim chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

Dim intLength As Integer = intStringLength - 1

Dim stringChars = New Char(intLength) {}

Dim random = New Random()

    For i As Integer = 0 To stringChars.Length - 1
        stringChars(i) = chars(random.[Next](chars.Length))
    Next

    Dim finalString = New [String](stringChars)
    Return finalString
End Function