Shuffling array using VB.NET

To Shuffling an array we use a function called ShuffleArray.
  • 8681
 

To Shuffling an array we use a function called ShuffleArray this function takes array as an argument, and return the value after shuffling to another array.

To perform this task you need to first create a new array same as the give array than randomly select all items from given array one by one and insert into the new array.

Sample Code

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 FirstArray As New ArrayList(argArr)
        Dim SecoundArray As Array = Array.CreateInstance(GetType(Object), FirstArray.Count)
        Dim intIndex As Integer
        For
i As Integer = 0 To FirstArray.Count - 1
            intIndex = RandomNumber(FirstArray.Count)
            SecoundArray(i) = FirstArray(intIndex)
            FirstArray.RemoveAt(intIndex)
        Next
        FirstArray = Nothing
        Return
SecoundArray
    End Function

    Private
Function RandomNumber(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
Module1
    Sub Main()
        Dim AU As ArrayUtilities
        AU = New ArrayUtilities
        Dim GivenArray As Integer() = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
        Dim NewArray As Array = AU.ShuffleArray(GivenArray)
        Dim i As Integer
        Dim
stb As New System.Text.StringBuilder
        stb.Append("GivenArray = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20}")
        stb.Append(vbCrLf)
        stb.Append(
"NewArray = {")
        For i = 0 To NewArray.Length - 2
            stb.Append(NewArray(i).ToString)
            stb.Append(
", ")
        Next
        stb.Append(NewArray(NewArray.Length - 1).ToString)
        stb.Append(
"}")
        Console.Write(stb.ToString)
        Console.Read()
    End Sub
End
Module

Output

1.gif

Conclusion

In this article you have learned how to shuffle an Array programmatically.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.