Reputation: 517
I am attempting to shuffle an array of strings, below is the segment of code i have already. However, a problem with this code is that alot of the times it shuffles the content but excludes one value. e.g shuffling A, B, C, D it will do this: A, D , , C.
Any help would be greatly appreciated.
Private rnd = New Random()
Public Sub Shuffle(ByRef List() As String)
Dim Limit As Integer = List.Length - 1
For i = Limit To 0 Step -1
Dim j As Integer = rnd.Next(0, i + 1)
Dim temp As String = List(i)
List(i) = List(j)
List(j) = temp
Next
End Sub
Upvotes: 1
Views: 97
Reputation: 125197
As a simple and clean option you can shuffle a list of string this way:
Public Function Shuffle(source As List(Of String)) As List(Of String)
Dim rnd = New Random(System.DateTime.Now.Millisecond)
Return source.OrderBy(Function(item) rnd.Next()).ToList()
End Function
And here is the usage:
Dim list = New List(Of String) From {"A", "B", "C", "D"}
Dim result = Shuffle(list)
MessageBox.Show(String.Join("," , result))
Upvotes: 1