Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffle an array in vba [duplicate]

I need to shuffle values in array with no duplications, what do i need to add in my code to avoid duplications

Function Resample(data_vector)


   n = UBound(data_vector)
   ReDim shuffled_vector(n)
   For i = 1 To n
      shuffled_vector(i) = data_vector(WorksheetFunction.RandBetween(1, n))
   Next i
End Function
like image 666
Jibek Sultanova Avatar asked Oct 22 '25 15:10

Jibek Sultanova


1 Answers

this will randomize the array:

Function Resample(data_vector() As Variant) As Variant()
    Dim shuffled_vector() As Variant
    shuffled_vector = data_vector
    Dim i As Long
    For i = UBound(shuffled_vector) To LBound(shuffled_vector) Step -1
        Dim t As Variant
        t = shuffled_vector(i)
        Dim j As Long
        j = Application.RandBetween(LBound(shuffled_vector), UBound(shuffled_vector))
        shuffled_vector(i) = shuffled_vector(j)
        shuffled_vector(j) = t
    Next i
    Resample = shuffled_vector
End Function

You can call like this:

Sub try()
    Dim x() As Variant
    x = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)

    x = Resample(x)

    MsgBox Join(x, ",")
End Sub

enter image description here

like image 132
Scott Craner Avatar answered Oct 25 '25 05:10

Scott Craner