Published:
26 Jun 2007
|
Abstract
In this code snippet Joseph demonstrates how to shuffle an array in a very simple and intuitive manner. |
|
by Joseph Chahine
Feedback
|
Average Rating:
Views (Total / Last 10 Days):
25106/
33
|
|
|
Introduction |
ShuffleArray is a function that takes an array as argument,
shuffles it, and returns another array holding the shuffled items.
|
Steps |
The steps of shuffling are as follows:
1.
Create a new array with the same dimension of the original array to be
shuffled.
2.
Select an item randomly from the original array and insert it in the new
array.
3.
Repeat the previous step until all items of the original array are
copied to the new array.
4.
Return the new array.
|
Code |
The example given below demonstrates how to implement the
above mentioned functionality.
Listing 1
Imports System.Security.Cryptography
Public Class ArrayUtilities
Private Random As RNGCryptoServiceProvider = New RNGCryptoServiceProvider
Private Bytes(4) As Byte
Public Function ShuffleArray(ByVal argArr As Array) As Array
Dim arr1 As New ArrayList(argArr)
'' Creating an array of Objects having the same dimension as the argument Array.
Dim arr2 As Array = Array.CreateInstance(GetType(Object), arr1.Count)
Dim intIndex As Integer
For i As Integer = 0 To arr1.Count - 1
'' intIndex is a random number between 0 and arr1.Count-1
intIndex = GenerateRandomNumber(arr1.Count)
arr2(i) = arr1(intIndex)
arr1.RemoveAt(intIndex)
Next
arr1 = Nothing
Return arr2
End Function
Private Function GenerateRandomNumber(ByVal argMax As Integer) As Integer
If argMax <= 0 Then Throw New Exception
Random.GetBytes(Bytes)
Dim intValue As Integer = (BitConverter.ToInt32(Bytes, 0)) Mod argMax
If intValue < 0 Then intValue = -intValue
Return intValue
End Function
End Class
Module TestModule
Sub Main()
Dim AU As ArrayUtilities
AU = New ArrayUtilities
Dim OriginalArray As Integer() = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
Dim ShuffledArray As Array = AU.ShuffleArray(OriginalArray)
Dim i As Integer
Dim stb As New System.Text.StringBuilder
stb.Append("OriginalArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}")
stb.Append(vbCrLf)
stb.Append("ShuffledArray = {")
For i = 0 To ShuffledArray.Length - 2
stb.Append(ShuffledArray(i).ToString)
stb.Append(", ")
Next
stb.Append(ShuffledArray(ShuffledArray.Length - 1).ToString)
stb.Append("}")
Console.Write(stb.ToString)
Console.Read()
End Sub
End Module
|
Analysis |
In order to view the result of the above snippet, you should
open and execute the Visual Studio 2005 project, which can be downloaded from
the link given in the Downloads section. The final output will look like the
figure below.
Figure 1
|
Downloads |
|
Summary |
In this article you have learned how to shuffle an Array
programmatically using Visual Basic 2005.
|
|
|
User Comments
No comments posted yet.
|
Product Spotlight
|
|