I need to generate n random numbers between a and b, but any two numbers cannot have a difference of less than c. All variables except n are floats (n is an int).
Solutions are preferred in java, but C/C++ is okay too.
Here is what code I have so far.:
static float getRandomNumberInRange(float min, float max) {
return (float) (min + (Math.random() * (max - min)));
}
static float[] randomNums(float a, float b, float c, int n) {
float minDistance = c;
float maxDistance = (b - a) - (n - 1) * c;
float[] randomNumArray = new float[n];
float random = getRandomNumberInRange(minDistance, maxDistance);
randomNumArray[0] = a + random;
for (int x = 1; x < n; x++) {
maxDistance = (b - a) - (randomNumArray[x - 1]) - (n - x - 1) * c;
random = getRandomNumberInRange(minDistance, maxDistance);
randomNumArray[x] = randomNumArray[x - 1] + random;
}
return randomNumArray;
}
If I run the function as such (10 times), I get the following output:
Input: randomNums(-1f, 1f, 0.1f, 10)
[-0.88, 0.85, 1.23, 1.3784, 1.49, 1.59, 1.69, 1.79, 1.89, 1.99]
[-0.73, -0.40, 0.17, 0.98, 1.47, 1.58, 1.69, 1.79, 1.89, 1.99]
[-0.49, 0.29, 0.54, 0.77, 1.09, 1.56, 1.69, 1.79, 1.89, 1.99]
I think a reasonable approach can be the following:
(b - a)(n-1)*cto obtain the remaining space(n-1)random numbers between 0 and 1 and scale them so that the sum is this just computed “optional space”. Each of them will be a “slice” of space to be used.acand the next “slice” to the previous number. Last number will beb.If you don’t want first and last to match
aandbexactly then just createn+1slices instead ofn-1and start witha+slice[0]instead ofa.The main idea is that once you remove the required spacing between the points (totalling
(n-1)*c) the problem is just to findn-1values so that the sum is the prescribed “optional space”. To do this with a uniform distribution just shootn-1numbers, compute the sum and uniformly scale those numbers so that the sum is instead what you want by multiplying each of them by the constant factork = wanted_sum / current_sum.To obtain the final result you just use as spacing between a value and the previous one the sum of the mandatory part
cand one of the randomly sampled variable parts.An example in Python of the code needed for the computation is the following