# shuffle an array

Hello there,
is it possible to make this more random or something because its half working.. for example I never got "snake" any ideas?

Dim animals() As String = {"cat", "dog", "snake"}
Debug.Print(Shuffle_Random_From_Array(animals))

``````    Function Shuffle_Random_From_Array(ByRef data() As String, Optional ByVal MoreThanOne As Integer = 0) As String
Dim Result As String = Nothing
Dim Rand As New Random
Dim daRandies As New ArrayList
Dim i As Integer = 0

For Each fern As String In data
Next

For inx As Integer = daRandies.Count - 1 To 1 Step -1
Dim position As Integer = Rand.[Next](inx)
Dim temp As Object = daRandies(inx)
daRandies(inx) = daRandies(position)
daRandies(position) = temp
Next

If MoreThanOne > 0 Then
For i = 1 To MoreThanOne
Result += daRandies.Item(i - 1) & ","
Next
Result = Result.Substring(0, Result.Length - 1)
Else
Result = daRandies.Item(0)
End If

Return Result
End Function
``````
LVL 1
###### Who is Participating?

Commented:
Ok here is the modifed version. I tested it and it retuerns all3 animals by random:

``````Imports System.Diagnostics

Module Module1

Sub Main()
Dim animals() As String = {"cat", "dog", "snake"}
Debug.Write(Shuffle_Random_From_Array(animals))

End Sub

Function Shuffle_Random_From_Array(ByRef data() As String, Optional ByVal MoreThanOne As Integer = 0) As String
Dim Result As String = Nothing
Dim Rand As New Random
Dim daRandies As New ArrayList
Dim i As Integer = 0

For Each fern As String In data
Next

For inx As Integer = daRandies.Count - 1 To 0 Step -1
Dim position As Integer = Rand.Next(0, 3)

Dim temp As Object = daRandies(inx)
daRandies(inx) = daRandies(position)
daRandies(position) = temp
Next

If MoreThanOne > 0 Then
For i = 1 To MoreThanOne
Result += daRandies.Item(i - 1) & ","
Next
Result = Result.Substring(0, Result.Length - 1)
Else
Result = daRandies.Item(0)
End If

Return Result
End Function

End Module
``````
0

Commented:
Here is the issue:

``````For inx As Integer = daRandies.Count - 1 To 1 Step -1
``````

daRandies.Count is 3  so this for only runs for inx=2 and inx=0

change it to:

``````For inx As Integer = daRandies.Count  To 1 Step -1
``````
0

Author Commented:
I get an error because there are 3 but 0,1,2 and not 1,2,3
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.