How to inform a c++ program not to pick a specific number within an established series of numbers?

In c++, if I want a program to choose a random number from a specific range of ordered numbers, for example: 1 to 9. How to I inform it to do so, however, not pick a specific number from within that range, like 7?

3 Answers

Relevance
  • 6 months ago

    There are multiple ways to achieve this. I would probably put a If/then statement in there to have it pick another random number. This gives you the flexibility to add as many numbers as you want that should not be counted and chose again.

  • 6 months ago

    Don't loop. There's an easier fix for two consecutive ranges like 1-6 and 8-9.

    There are 9-1 = 8 numbers actually "in play", so generate n as a random number between 1 and 8 inclusive. Then if n >= 7, add 1 to n.

    That way you get the full period of your random generator, not throwing away any of them, and every number is equally likely (provided that the original 1-8 choice was uniformly random.)

    You can extend that idea to a larger single gap by conditionally adding a number larger than 1; and to multiple gaps by adding multiple if statements.

  • 6 months ago

    You cannot generate a random number that will have gap in the distribution.

    So, the best way is to pick a random number and check it. If it picked 7, then you loop back and pick again.

    Alternatively, you could have an array of dimension 8 that contains the number from 1 to 9, except 7.

    Then you get a random number from 1 to 8, and that number is the index to the array. If it picked 7, then it would return the number in the 7th slot, which is 8.

    (actually since c++ have array index starting at 0, it would be from 0 to 7, but you get the idea).

    The down size is that you have to have that pre-populated array.

Still have questions? Get answers by asking now.