0

Now sure if the title describes what I really want but a live example is always better. I want to generate a random number between 2 integer values (100, 1000) but only with a 50 step so accepted answers should be 100 or 150 or 450 or 500 or 750 or 800 etc.

I know a simple random should be done like this:

Random random = new Random();
int randomNumber = random.Next(100, 1000);

1 Answers1

11
int randomNumber = random.Next(2, 20) * 50;

Basically, you cannot skip numbers within the range (that would remove the randomness property), so just generate coherent random numbers and map them to your desired target number set.

In your case, this is very easy since you have a fixed step size. But this works even with more complex stuff; worst case, you create an injective function that maps one random number to one number in your target space. This also allows you to get different distributions (e.g. making a die where certain numbers are more likely than others).

poke
  • 369,085
  • 72
  • 557
  • 602
  • I was thinking about `Math.Round` but thats an added step :) – EpicKip Mar 15 '17 at 08:12
  • 3
    Just incase it's not immediately obvious, one arrives at the above with `random.Next(minSize / step, maxSize / step) * step` – Rob Mar 15 '17 at 08:14
  • 2
    @EpicKip Be careful with rounding random numbers. That quickly destroys the randomness. For example `Math.Round(random.Next(20) / 10.0))` has a distribution of 30%, 45%, and 25% for 0, 1, and 2 respectively, because of the “smart” rounding behavior of `Math.Random`. – poke Mar 15 '17 at 08:18