Recipe 8.5. Shuffling an Array


Problem

You want to randomize the order of the elements in an array efficiently.

Solution

Sample code folder: Chapter 08\ShuffleArray

Write a routine that randomly rearranges the elements of an array. The code in this recipe does this using an array of any data type.

Discussion

The Shuffle() method presented here swaps each element of the array with a randomly selected element from elsewhere in the array. Sometimes this may cause an element to be swapped with itself, but that doesn't make the results any less random. By sequencing through all elements, the algorithm guarantees that each one will be swapped at least once:

 Public Sub Shuffle(ByRef shuffleArray( ) As Object)    ' ----- Reorder the elements of an array in a random order.    Dim counter As Integer    Dim newPosition As Integer    Dim shuffleMethod As New Random    Dim tempObject As Object    For counter = 0 To shuffleArray.Length - 1       ' ----- Determine the new position.       newPosition = shuffleMethod.Next(0, _          shuffleArray.Length - 1)       ' ----- Reverse two elements.       tempObject = shuffleArray(counter)       shuffleArray(counter) = shuffleArray(newPosition)       shuffleArray(newPosition) = tempObject    Next counter End Sub 

The following code creates a string array of fruit names, shuffles the array, and displays the array contents both before and after the shuffling:

 Dim result As New System.Text.StringBuilder Dim arrayShuffle( ) As String = { _    "Oranges", "Apples", "Grapes", "Bananas", "Blueberries"} ' ----- Show the pre-random results. result.AppendLine("Before shuffling:") For Each fruit As String In arrayShuffle    result.AppendLine(fruit) Next fruit ' ----- Randomize. Shuffle(arrayShuffle) ' ----- Show the post-random results. result.AppendLine( ) result.AppendLine("After   shuffling:") For Each fruit As String In arrayShuffle    result.AppendLine(fruit) Next fruit MsgBox(result.ToString( )) 

Figure 8-5 shows the results from running the sample code, listing the array's contents before and after the shuffling. Your output may vary due to the random nature of the test.

Figure 8-5. Randomizing an array's elements with the Shuffle( ) method


See Also

Recipe 8.6 uses a portion of this recipe's code to generically reverse two array elements.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net