0

I'm trying to generate a list of 10 random numbers. I have some ranges like:

  1. 0 to 9
  2. 10 to 99
  3. 100 to 999
  4. 1000 to 9999
  5. 10000 to 99999
  6. 100000 to 999999.

If I generate a random number in a (min, max) range where min = 0 and max = 999999 with this code

import 'dart:math';
final _random = new Random();
   
int next(int min, int max) => min + _random.nextInt(max - min);

a number between 100000 and 999999 is more likely to be generated than a number between 0 and 9. This is because there are more numbers in the range (100000, 999999) than in the range (0,9). If I pick a random number from 0 to 999999, it's more likely that is a number in the range 5).

I would like to generate 10 random numbers in the given ranges with equal probability for each range.

  • Using the random number generator, determine what range you're generating (e.g. labelling each range from `0` to `5`, generate a number between those inclusively). Then use the generator again to generate a random number within the selected range. – Rogue Jan 02 '22 at 11:57
  • 1
    Does this answer your question? [How do I generate random integers within a specific range in Java?](https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java) – Peter O. Jan 02 '22 at 11:59
  • @Rogue That could be a good solution. Thanks! – Biagio Iorio Jan 02 '22 at 12:08
  • Sorry @PeterO. but the answer does not seem to take into account the probability for each different range. – Biagio Iorio Jan 02 '22 at 12:11
  • 2
    2 things are not clear to me in your question: 1) why `nextInt(max - min)` in your code instead of the `nextInt(max)`? 2) not really clear what exactly you mean in `a number between 100000 and 999999 is more likely to be generated than a number between 0 and 9.`. The probability density is ~uniform in the range. – Alexander Arendar Jan 02 '22 at 12:27
  • 1
    Java or Dart? Fix your tags. – Basil Bourque Jan 02 '22 at 14:32
  • @AlexanderArendar 1) Because in this way I can also choose to start from a range other than range 0); 2) Yes, the probability is uniform within every single range, but not uniform in the total (from 0 to 999999). I edited the question to clarify this point. – Biagio Iorio Jan 02 '22 at 16:43

1 Answers1

0

I'd pick the range first, then find the number in that range.

Consider:

var _rnd = Random();
int inRanges() {
  var powerOfTen = _rnd.nextInt(6);
  var min = pow(10, powerOfTen) as int;
  var max = min * 10 - 1;
  if (min == 1) min = 0; // The cases are not completely symmetric.
  return min + _rnd.nextInt(max - min);
}
lrn
  • 64,680
  • 7
  • 105
  • 121