我已经看过很多教程,但似乎对我没什么用。我需要生成随机数而不重复。
这是我的代码:
Dim intNumber As Integer
Dim arrNumber(0 To 0) As Integer
Dim i, x, y As Integer
'Make sure the Label is clear
Label1.Text = ""
For x = 0 To 0
Start:
intNumber = Int((25 * Rnd()) + 1) ' Random number 1 to 25
For y = 0 To 0
' Check arrNumber (y)
'If intnumber has already been selected,
'Then go and select another one.
If intNumber = arrNumber(y) Then
GoTo Start
End If
Next y
'Place the next non-repeated number in the arrNumber(x).
arrNumber(x) = intNumber
Next x
'----------------------------------------------------
For i = 0 To 0
Label1.Text = Label1.Text & (arrNumber(i))
broj1.random.Text = Label1.Text
Next
End Sub
答案 0 :(得分:1)
你的问题是,特别是在vb中,难以解决。您正在寻找随机交易而不是随机滚动。也就是说,您正在寻找赌场经销商的模拟一张接一张地拖着25张卡片,而不是经销商转动一个25格的轮盘赌。
让事情变得艰难的一件事就是第26张牌。改组?处理相同的订单?
这是一篇关于这个主题的体面论文。 http://www.4guysfromrolla.com/articles/070208-1.aspx
这里有一些C#代码要处理。
private static List<int> _deck = null;
private static readonly Random NumberGenerator = new Random();
public static int Deal()
{
if (_deck == null || _deck.Count == 0)
{
/* new deck */
_deck = new List<int>();
for (var i = 0; i <= 24; i++) _deck.Add(i);
}
/* get a random card from the remaining deck */
var next = NumberGenerator.Next(0, _deck.Count);
/* retrieve the card's number */
var q = _deck[next];
/* and remove the card from the deck */
_deck.RemoveAt(next);
/* return in range 1-25 */
return q + 1;
}
答案 1 :(得分:1)
有时您需要学习如何构建时钟,有时您只需知道时间:
Const HowMany As Integer = 25 ' how many numbers do you want?
Dim Used As New List(Of Integer)
Used.Add(0) ' position zero has 0, all other positions have a generated counting number
For i = 1 To HowMany
Dim OK As Boolean = False ' OK becomes true when a unique number has been generated
Do
Dim num As Integer = Int((HowMany * Rnd()) + 1)
If Used.Contains(num) Then
OK = False ' we'll try again shortly
Else
OK = True ' this round is complete -- found a unique number
Used.Add(num) ' add the generated number to the list
End If
Loop Until OK ' in other words, loop until we've found a unique number
Next
For i = 1 To HowMany
MsgBox(Used(i)) ' or just use the list in however you need
Next