所以我试图创建一个我可以输入一个arraylist的函数,然后该函数从该arraylist中随机选取X个项目并将结果输出到一个新的arraylist。我已经开始工作了,我遇到的问题是,在随机选择其中一个项目之后,它仍然存在,这意味着它可以再次被选中。这是我到目前为止的代码
Dim RandomGeneratorMulti As New ArrayList()
Dim resultMulti As New ArrayList()
RandomGeneratorMulti.Add("Happy")
RandomGeneratorMulti.Add("Sad")
RandomGeneratorMulti.Add("Smart")
RandomGeneratorMulti.Add("Intelegt")
RandomGeneratorMulti.Add("Stupid")
RandomGeneratorMulti.Add("Ugly")
ChooseMulti("5", RandomGeneratorMulti)
TraitsListBox.Items.AddRange(resultMulti.ToArray)
这是函数
Function ChooseMulti(ByVal Numbers As Integer, ByVal Alist As ArrayList) As ArrayList
Dim rnd = New Random()
For i As Integer = 1 To Numbers
resultMulti.Add(Alist.Item(rnd.Next(0, Alist.Count)))
Next
Return resultMulti
End Function
非常感谢所有帮助:)
答案 0 :(得分:1)
您应该使用List(Of String)
而不是ArrayList
,但我使用ArrayList
编写了以下代码,以便它更接近原始代码。
您可以从列表中删除您选择的项目:
Function ChooseMulti(ByVal numbers As Integer, ByVal Alist As ArrayList) As ArrayList
Dim resultMulti As New ArrayList()
Dim rnd = New Random()
For i As Integer = 1 To numbers
Dim index As Integer = rnd.Next(Alist.Count)
resultMulti.Add(Alist.Item(index))
Alist.RemoveAt(index)
Next
Return resultMulti
End Function
注意:当您从函数返回列表时,您应该获得返回值并放入resultMulti
变量,而不是从函数内部更改变量:
resultMulti = ChooseMulti(5, RandomGeneratorMulti)
另一种方法是将列表洗牌(使用Fisher-Yates shuffle),然后取出第一项:
Function ChooseMulti(ByVal numbers As Integer, ByVal Alist As ArrayList) As ArrayList
Dim resultMulti As New ArrayList()
Dim rnd = New Random()
For i As Integer = Alist.Count - 1 to 1 Step -1
Dim index = rnd.Next(i + 1)
Dim temp As String = Alist(i)
Alist(i) = Alist(index)
Alist(index) = temp
Next
For i As Integer = 0 To numbers - 1
resultMulti.Add(Alist.Item(i))
Next
Return resultMulti
End Function
另一种方法是从头到尾从列表中选择数字。这样就不会有重复,原始列表保持不变,但副作用是所挑选的项目与原始列表中的顺序相同:
Function ChooseMulti(ByVal numbers As Integer, ByVal Alist As ArrayList) As ArrayList
Dim resultMulti As New ArrayList()
Dim rnd = New Random()
Dim index As Integer = 0
While numbers > 0
If rnd.Next(Alist.Count - index) < numbers Then
resultMulti.Add(Alist.Item(index))
numbers -= 1
EndIf
index += 1
Wend
Return resultMulti
End Function