Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating an Array of Random Numbers with Minimum Spacers/Distribution?

i'm attempting to populate an array with random numbers, but the random numbers must be a certain, minimum distance apart from each other.

i've populated an array with 5 random numbers between 0 - 100:

private var myArray:Array = new Array();

for (var i:uint = 0; i < 5; i++)
    myArray.push(Math.round(Math.random() * 100));

next i've sorted the array in numeric order:

myArray.sort(Array.NUMERIC);

after populating and sorting let's assume that myArray now contains these values:

26, 27, 42, 92, 97

now i would like some ore all of the array values to be reset, if they need to be, so that they are at least a certain percentage (let's say 10%) of the maximum value (100) apart from each other.

the first 2 values (26 and 27) are not at least 10% apart and neither are the last 2 values (92 and 97). however, if i simply moved the value 27 10% away from 26, so that 27 changes to 37, 37 now conflicts with the next value of 42.

what is the best approach for populating an array of random numbers who's values will be at least a certain percentage apart from one another but still random.

it may go without saying, but i'm looking for a solution that is portable, where maximum values and minimum distribution percentages can be anything, not just for my example above.

like image 366
Chunky Chunk Avatar asked Feb 05 '11 16:02

Chunky Chunk


1 Answers

In your case you want 5 numbers, all at least 10 from each other. What you should do is create 5 numbers from 0 to 60, sort them, then start adding the dividers in. So if your original list is 26, 27, 42, 52, 57 then your new list is 26, 27+10, 42+20, 52+30, 57+40 or 26, 37, 62, 82, 97.

This can be generalized to any desired range, number of elements and size of divider. If you want n elements with at least d dividing them in a range from x to y, then populate n elements in the range (x, y - (n-1)*d), sort them, and start adding the dividers in.

like image 125
btilly Avatar answered Nov 04 '22 04:11

btilly