Link to home
Start Free TrialLog in
Avatar of XK8ER
XK8ERFlag for United States of America

asked on

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
            daRandies.Add(fern)
        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

Open in new window

Avatar of unknown_routine
unknown_routine
Flag of United States of America image

Here is the issue:

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

Open in new window


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

Open in new window

Avatar of XK8ER

ASKER

I get an error because there are 3 but 0,1,2 and not 1,2,3
ASKER CERTIFIED SOLUTION
Avatar of unknown_routine
unknown_routine
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial