I am trying to generate random intervals between the range: 2,5k – 10M.
Currently, I am doing the following:
const MIN_NUMBER = 2500;
const MAX_NUMBER = 10000000;
const random = (min, max, floating = false) => {
const result = Math.random() * max + min;
return floating ? result : Math.floor(result);
};
const min = random(MIN_NUMBER, MAX_NUMBER / 10);
const max = random(min, min * 10);
const interval = `[${min}, ${max}]`;
console.log(interval);
But as you can see, the probability that the generated interval is small/medium is not very high.
I want to get random intervals like:
- [2500, 10400]
- [2500, 9919]
- [3000000, 3301029]
- [500000, 611223]
I am not following any specific rule, but as you can see, in relation with
- [2500, 400000]
- [2500, 71000]
- [3000000, 10000000]
- [500000, 3120000]
they are considered "small/medium", because there is not a "really huge" diff between the max and the min).
With my current algorithm, you can check that the generated average diff is high:
const MIN_NUMBER_OF_LIKES = 2500;
const MAX_NUMBER_OF_LIKES = 10000000;
const random = (min, max, floating = false) => {
const result = Math.random() * max + min;
return floating ? result : Math.floor(result);
};
let averageDiff = 0;
const numIterations = 1000;
for (let i = 0; i < numIterations; i++) {
const min = random(MIN_NUMBER_OF_LIKES, MAX_NUMBER_OF_LIKES / 10);
const max = random(min, min * 10);
averageDiff += max - min;
}
averageDiff /= numIterations;
console.log({ averageDiff });
How can I do for getting random small segments instead?
–Note: the difference between the randomly generated intervals is random too, but it has to be "small/medium" (not as huge as with my current solution).
>Solution :
What about first choosing random size of interval within the size you wish – so you get the value of INTERVAL_SIZE. As second step you randomly find the minimum between MIN_NUMBER_OF_LIKES and MAX_NUMBER_OF_LIKES – INTERVAL so you get STARTPOINT.
So final INTERVAL will have STARTPOINT and ENDPOINT = STARTPOINT + INTERVAL_SIZE