0

如何以随机顺序(随机播放)更改列表中的数据顺序。最简单的方法,最少的编码工作,无需定义新功能或子请。

4

2 回答 2

1

我通常用随机数据标记项目并对其进行排序。您可以直接实现洗牌,但这需要更多的工作 - 特别是证明算法实际上是随机洗牌......

于 2013-08-10T18:25:06.237 回答
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
于 2013-11-17T20:37:26.783 回答