50 未満の乱数を生成したいのですが、その数が生成されたら、再度生成できないようにしたいと考えています。
助けてくれてありがとう!
参照してください: 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 ~ 49 の数字を並べ替え可能なコレクションに入れ、ランダムな順序で並べ替えます。必要に応じて、コレクションからそれぞれをポップします。
質問に 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
以下のコードは、パラメータとして渡す長さの英数字文字列を生成します。
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