如何在随机顺序(Shuffle)中更改列表中的数据顺序。最简单的编码工作方法,无需定义新函数或sub please。
答案 0 :(得分:1)
我通常用随机数据标记项目并对其进行排序。你可以直接实现shuffle,但这样做更有效 - 特别是证明算法实际上是随机混乱...
答案 1 :(得分:0)
好吧,我刚刚在此处创建了此代码段以供将来参考,如果您想使用列表,只需将“Stack”的所有实例替换为“List”,并确保将“.Push”更改为“.Add”它应该工作正常。说实话,我很惊讶没有内置的随机播放功能。
Dim Deck As New Stack
Sub Main()
For i As Integer = 1 To 10
Deck.Push("Card #" & i)
Next
Do
Console.Clear()
For i As Integer = 0 To Deck.Count - 1
Console.WriteLine(Deck(i))
Next
Console.ReadKey(True)
Shuffle()
Loop
End Sub
Private Sub Shuffle()
Dim NewDeck As New Stack
Dim i As Integer
Dim s As String 'Change type depending on what is in your stack.
Dim r As New Random
Do
i = r.Next(0, Deck.Count)
s = Deck(i)
'Stops you getting several of one item and then none of others, etc.
If Not NewDeck.Contains(Deck(i)) Then
NewDeck.Push(s)
End If
Loop Until NewDeck.Count = Deck.Count
Deck = NewDeck
End Sub