Home > Software design >  Replace items in an array by random items of reference Array
Replace items in an array by random items of reference Array

Time:03-11

I have two Array:

randomArray= Array("dog", "cat", "fish")
inputArray= Array("dog", "dog", "cat", "cat", "cat", "dog", "fish", "fish", "fish")

How can replace inputArray items using random items from randomArray to create outputArray like below:

outputArray= Array("fish", "fish", "dog", "dog", "dog", "fish", "cat", "cat", "cat")

As you can see for example all "dog" words replace with "fish". its not simple to use if statement, because randomArray have about 500 items and inputArray have about 6000 items. I can use loops for that, but my problem is that in this method, the items change over and over again during the cycles, which both increases the time and decreases the variety of items in the output array.

I think the best way is rearrange index of all same items. for example changes inputArray(1) and inputArray (2) to inputArray(10) and inputArray (11). and inputArray(7) and inputArray (8) inputArray(9) to inputArray(1) and inputArray (2) inputArray(3).

how can do that?

CodePudding user response:

Sub generateRandomArray()

    randomArray = Array("dog", "cat", "fish")
    inputArray = Array("dog", "dog", "cat", "cat", "cat", "dog", "fish", "fish", "fish")
    outputArray = inputArray
    
    low = LBound(randomArray)
    high = UBound(randomArray)
    If low = high Then
        Exit Sub
    End If
    
    Dim usedString As String: usedString = ""
    Dim randomIndex As Integer
    Dim i As Long, j As Long
    For i = low To high
        Randomize
        randomIndex = i
        While randomIndex = i Or InStr(1, usedString, randomArray(randomIndex))
            randomIndex = Int((high - low   1) * Rnd   low)
        Wend
        
        usedString = usedString & "." & randomArray(randomIndex)
        For j = LBound(inputArray) To UBound(inputArray)
            If inputArray(j) = randomArray(i) Then
                outputArray(j) = randomArray(randomIndex)
            End If
        Next j
    Next i

End Sub
  •  Tags:  
  • vba
  • Related