Random Number but Don't Repeat

后端 未结 4 1874
轻奢々
轻奢々 2020-12-02 03:12

I would like to generate a random number less than 50, but once that number has been generated I would like it so that it cannot be generated again.

Thanks for the h

相关标签:
4条回答
  • 2020-12-02 03:37

    Please see: 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;
        }
    }
    
    0 讨论(0)
  • 2020-12-02 03:39

    Below code generate alpha-numeric string with length that you pass as parameter.

    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
    
    0 讨论(0)
  • 2020-12-02 03:43

    Put the numbers 1-49 in a sortable collection, then sort it in random order; pop each one out of the collection as needed.

    0 讨论(0)
  • 2020-12-02 03:58

    Seeing as the question was tagged VB/VB.Net... this is a VB implementation of Mitch's answer.

    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
    
    0 讨论(0)
提交回复
热议问题