0

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?

1
  • It's not clear what your logic is for replacement. Only one unique value (and all replicates) are to be replaced in inputArray What if the random value picked from randomArray was "dog" in this case - then d nothing? Commented Mar 10, 2022 at 18:06

1 Answer 1

1
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
Sign up to request clarification or add additional context in comments.

2 Comments

But I need an array that has exactly the same number of repetitions of its items as the inputarray and only the item is different. repetitions index same as inputArray but value are different. 2 fish, 3 dog, 1 fish and 3 cat.
its worked, great

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.