我能够生成一个随机数,但我无法做的是防止随机数重复。我希望它没有重复的数字。到目前为止,这是我的代码,
Dim rndnumber As Integer
Randomize()
rndnumber = Int(Rnd() * 52) + 1
ListBox1.Items.Add(rndnumber)
答案 0 :(得分:2)
这对我看起来很像牌,这意味着你真正想做的是 shuffle 牌组。当然,改组的最佳算法是Fisher-Yates Shuffle。
Private rand As New Random()
Public Function Shuffle(Of T)(ByVal items As IList(Of T)) As IList(Of T)
For i As Integer = items.Count - 1 To 1 Step -1
Dim j As Integer = rand.Next(i + 1)
Dim temp As T= items(i)
items(i) = items(j)
items(j) = temp
Next
Return items
End Function
ListBox1.Items.AddRange(Shuffle(Enumerable.Range(0,52).ToList()).ToArray())
答案 1 :(得分:0)
'这个有趣的程序,用于向朋友们介绍VB 2010
公共类表格1
Private miNdx As Integer, miSaveVerb As Integer
Private miSaveWhat As Integer, miSaveWith As Integer, miSaveWhere As Integer
Private msVerbs(6) As String
Private msWhat(6) As String
Private msWhere(6) As String
Private msWhile(6) As String
Private Sub cmdGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGo.Click
Dim iRnd As Integer
Dim sVerb As String, sWhat As String, sWhere As String, sWhile As String
iRnd = RNDGenerator(miSaveVerb)
sVerb = msVerbs(iRnd)
iRnd = RNDGenerator(miSaveWhat)
sWhat = msWhat(iRnd)
iRnd = RNDGenerator(miSaveWhere)
sWhere = msWhere(iRnd)
iRnd = RNDGenerator(miSaveWith)
sWhile = msWhile(iRnd)
Me.txtDisplay.Text = Me.txtName.Text & sVerb & sWhat & sWhile & sWhere
End Sub
Private Function RNDGenerator(ByRef iSave As Integer) As Integer
Dim i As Integer
Randomize()
Do
i = Int(miNdx * Rnd() + 1)
Debug.Print(i)
Loop While iSave = i
iSave = i
RNDGenerator = i
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.txtDisplay.Text = vbNullString
Me.txtName.Text = vbNullString
miNdx = 6
msVerbs(1) = " eats"
msVerbs(2) = " smashes"
msVerbs(3) = " pukes"
msVerbs(4) = " sucks"
msVerbs(5) = " farts"
msVerbs(6) = " licks"
msWhat(1) = " shit"
msWhat(2) = " scum"
msWhat(3) = " dirt"
msWhat(4) = " filth"
msWhat(5) = " scabs"
msWhat(6) = " boogers"
msWhere(1) = " in my house"
msWhere(2) = " in the bathroom"
msWhere(3) = " in the kitchen"
msWhere(4) = " in a Sandbox"
msWhere(5) = " at the whore house"
msWhere(6) = " in a muddy hole"
msWhile(1) = " while smiling"
msWhile(2) = " while making puke puddles"
msWhile(3) = " while playing with poop"
msWhile(4) = " while smelling farts"
msWhile(5) = " while stinking bad"
msWhile(6) = " while laughing"
End Sub
结束班级
答案 2 :(得分:-3)
代码从ArrayList生成随机选择(因此可能是整数,字符串,图像文件等) - 这里只有52个整数来表示一组卡片。 代码确保通过从输入ArrayList中删除项目无法选择重复项。随机选择被添加到输出ArrayList(或在问题中请求到ListBox)
Dim RandNo as new Random
Dim Deck as ArrayList
Dim Shuffle as ArrayList 'or just use ListBox as in Question
For Counter = 0 to 51
'Just integers to represent the 52 cards, but could be Strings 5D, 6H etc
'or even card images
Deck.Add(Counter)
Next
Dim Temp as Integer
For Counter = 0 to 51
Temp = Deck.Item(RandNo.Next,0,Deck.Count - 1))
Shuffle.Add(Temp) 'or for question - ListBox1.Items.Add(Temp)
Deck.Remove(Temp)
Next