How to shuffle a list on a random order?

How can I change the order of data in a list on a random order (Shuffle). easiest method with the least coding effort without definition of new functions or sub please.

Upvotes: 0

Views: 2268

Answers (2)

Ethan K.
Ethan K.

Reputation: 1

Well, I just made this code snippet here for a future reference, if you want to use a list just replace all instances of "Stack" with "List" and make sure to change ".Push" to ".Add" and it should work fine. To be honest I'm surprised a shuffle function isn't built in.

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

Upvotes: 0

vbar
vbar

Reputation: 11

I usually tag the items with random data and sort that. You can implement the shuffle directly, but that's more work - especially proving the algorithm actually shuffles randomly...

Upvotes: 1

Related Questions