I’m using javascript and here is the problem statement
const sourceArray = [3, 6, 9]
const elementsToGenerate = 10
expected output is random numbers from sourceArray till the length of the output array is 10 and should have at least 1 of each element from sourceArray and should be spread almost evenly
example output 1 [3,9,6,6,3,9,6,3,3,9]
example output 2 [9,6,3,9,6,9,3,9,3,6]
2
Answers
You need to ensure that all unique elements from the source array exist in the output, so start with the unique elements from the source array.
Then, add as many random values from the source array as required to reach the target number.
Calculate the frequency of each unique number in the array. For each unique number, determine the indices it should be at in the target array when spread out evenly.
There will be clashes where more than one number wants to be in a certain position, but that’s ok – we can just allow one to follow the other. We sprinkle in Number.EPSILON, which is a tiny number, in order to prevent the index sort process from clumping the results when more than one value wants to be at the same index.
To match the above requirements I suggest creating a pseudorandom array where the number of elements is spread evenly
[3, 6, 9, 3, 6, 9, 3, 6, 9]