Shuffle the elements of array in vb.net
Vb program for Shuffle the elements of array. Here problem description and explanation.
' Include namespace system
Imports System
' Vb.net program for
' Shuffle the array elements
public Class Shuffling
' Function which is swapping two list elements
' of given location
Public Shared Sub swapElement(ByVal arr As Integer(),
ByVal i As Integer, ByVal j As Integer)
' Get i location element
Dim temp As Integer = arr(i)
' Set new values
arr(i) = arr(j)
arr(j) = temp
End Sub
' Returns the random location of list elements
Public Shared Function randomLocation(
ByVal min As Integer, ByVal max As Integer) As Integer
' Calculate random number between given range
Dim rand As Random = New Random()
return rand.Next(min, max+1)
End Function
' Function which is shuffle given list elements
Public Shared Sub shuffleElement(ByVal arr As Integer(),
ByVal size As Integer)
' (i,j) indicate locations
Dim j As Integer = 0
Dim i As Integer = 0
' Variable which is controlling the
' execution process of loop
Dim counter As Integer = 0
' Loop which is shuffling random elements in list
while (counter < size)
' Get random location of list index
i = randomLocation(0, size - 1)
j = randomLocation(0, size - 1)
if (i <> j) Then
' Swap list elements
swapElement(arr, i, j)
counter += 1
End If
End While
End Sub
' Function which is display list elements
Public Shared Sub display(ByVal arr As Integer(),
ByVal size As Integer)
Dim i As Integer = 0
While i < size
' Disply element value
Console.Write(" " + arr(i).ToString())
i += 1
End While
Console.WriteLine()
End Sub
Public Shared Sub Main(ByVal args As String())
' Define list of integer elements
Dim arr As Integer() =
{1, 0, -3, 8, 7, 3, 9, 4, 2, 5, 10, 6}
Dim size As Integer = arr.Length
' Before shuffling list elements
Console.WriteLine(" Initial array elements")
display(arr, size)
Console.WriteLine(" After Shuffle array elements")
shuffleElement(arr, size)
display(arr, size)
shuffleElement(arr, size)
display(arr, size)
shuffleElement(arr, size)
display(arr, size)
End Sub
End Class
Output
Initial array elements
1 0 -3 8 7 3 9 4 2 5 10 6
After Shuffle array elements
4 5 8 1 7 10 9 6 0 3 2 -3
9 5 6 1 7 10 8 0 -3 2 3 4
9 5 4 2 8 -3 1 7 6 10 3 0
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment