Looking for advice on optimizing a function I'm developing. My goal is to:
Double the frequency of numbers in an array
Randomize the location of the values in the array.
For instance: Imagine I have an array. [0,1,2,3]
First, I need to duplicate each number in a new array. Resulting in:
[0,0,1,1,2,2,3,3]
.Then, I want to randomize these values to get:
[0,4,2,3,0,2,3,4]
The algorithm needs to be able to handle an initial array of 18 digits (resulting in a final, randomized array of size 36)
My initial approach involves using a simple while loop that:
- Randomly picks a spot in the new array
- Checks if the spot is filled -If it is, repeat the process
- If it's empty, place the value and move on to the next
I'm simplifying here, but I want the algorithm to be efficient to avoid delays.
I'm concerned that once there's only one spot left, the algorithm might take longer to place it due to the odds.
How can I improve the algorithm to make it quicker and more effective?
Thanks in advance!