creating a shuffle method?

tahu191

Well-known member
Joined
Oct 27, 2005
Messages
48
Location
USA
Programming Experience
Beginner
I am trying to create a method that "shuffles" around the elements in an array of images, here is what i have now:

VB.NET:
        Dim i1(32) As Bitmap
Dim count As Integer =  32
        Do
            Dim a As Integer = Rnd() * count
            Dim i As Image = images1(a)
            If i.Equals(Nothing) = False Then
                i1((32) - count) = i
                count -= 1
            End If
        Loop While count > 0

        For x As Integer = 0 To i1.Length - 1
            images1(x) = i1(x)
        Next

What it does is take random elements from the original array and assign them to a temporary one. Then when all of them are done it assigns them back to the real array. It isn't working 100%
 
The best way to do this is with a collection:
VB.NET:
Dim myList As New List(Of BitMap)(myArray)
Dim listIndex As Integer

For arrayIndex As Integer = 0 To myArray.GetUpperBound(0)
    listIndex = myRandom.Next(0, myList.Count)
    myArray(index) = myList(listIndex)
    myList.RemoveAt(listIndex)
Next index
Note that you do NOT use the Randomize and Rnd functions. You create a Random object and use its Next method.
 
Shuffle Sort Algorithm

This is an established algorithm that shuffles an array of any size randomly without duplicates or omissions. It works by rearranging the indexes randomly after values have been assigned, using a swap routine. This example uses an integer array, assigns sequential values and displays the results in a textbox. But any values may be assigned prior to the swap routine, and any type array can be used. The temp variable should be the same type as the array.

======================================================
Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
Dim x, mix, temp As Integer
Dim num As Integer = 20
Dim randarray(num) As Integer
Dim randnum As New Random

For x = 1 To num
randarray(x) = x
Next x

For x = 1 To num
mix = randnum.Next(1, num + 1)
temp = randarray(mix)
randarray(mix) = randarray(x)
randarray(x) = temp
Next x

txtShuffle.Clear()
For x = 1 To num
txtShuffle.Text &= randarray(x).ToString & " "
Next x
End Sub
 
Last edited:
Back
Top