Reputation: 1458
I'm trying to shuffle elements between a certain number of indexes.
Dim rng As New Random()
For placeHolder As Integer = min To max Step -1
Dim swapIndex As Integer = rng.Next(min, max)
Dim temp As Object = myList(placeHolder)
myList(placeHolder) = myList(swapIndex)
myList(swapIndex) = temp
Next
Where 'min' is the value of the lowest index and 'max' is the value of the highest index. However each time I have tried it doesn't seem to be shuffling randomly (it always comes out alphabetically instead).
Upvotes: 0
Views: 149
Reputation: 938
Try this:
Dim rng As New Random()
For placeHolder as Integer = min To max-1 Step 1
Dim swapIndex as Integer = rng.Next(placeHolder +1, max)
Dim temp as Object = myList(placeHolder)
myList(placeHolder) = myList(swapIndex)
myList(swapIndex) = temp
Next
The changes? I changed the max value being stepped over to 1 less than the end so that you don't waste time trying to swap the end with itself. I also changed the Step to +1 because min < max from your description. I changed the minimum random value to placeholder + 1 because I don't want to re-swap what I've already swapped. This last change is optional though.
Upvotes: 1
Reputation: 6255
if min
is the lowest and max
is the highest, then your loop should not have Step -1
in it. That will cause the loop to never execute.
Upvotes: 0