1

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
3
  • Dim j As Integer = rnd.Next(0, Limit + 1) not sure if it is related but you want to make sure each element is considered for swap at least once Commented Oct 28, 2015 at 19:06
  • 1
    You are not providing enough information (= original values in List), but your problem has most likely to do with the fact that the list contains a blank value which is being included in the shuffling. Commented Oct 28, 2015 at 19:11
  • Cannot reproduce - 500 reps and nothing was skipped/dropped. Make sure you dont have any empties in your array Commented Oct 28, 2015 at 19:24

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.