CodeSnip: Simple Array Shuffler
page 3 of 6
by Joseph Chahine
Feedback
Average Rating: 
Views (Total / Last 10 Days): 25123/ 66

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 IntegerAs 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

View Entire Article

User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-05-18 6:02:18 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search