-2

I would like to get a random number between two intervals, 1, 4 and 8, 16

To get a random number between one interval I would have to do this:

randNumber = random(1, 3);

What if I wanted my variable to have the possibility to be a number between 8 and 16 too, and not only between 1 and 4?

Thank you.

Banha Dix
  • 113
  • 1
  • 10
  • 1
    Populate a container with all your pool numbers, then generate a random number that will behave as an index for that container. Then generate random index and pick your value. Here is how to generate within a range [**Generating random integer from a range**](http://stackoverflow.com/questions/5008804/generating-random-integer-from-a-range) or just use the % module with respect to the size of your container. – Khalil Khalaf Jul 26 '16 at 20:33
  • 1
    Use `std::uniform_int_distribution` and set the required limits. – sjrowlinson Jul 26 '16 at 20:33
  • 1
    I think OP is looking for [`std::piecewise_constant_distribution`](http://en.cppreference.com/w/cpp/numeric/random/piecewise_constant_distribution). – LogicStuff Jul 26 '16 at 20:43
  • 1
    Because I can't post any answers so here: **If** `std::vector NumbersPool = { 1,2,3,4,8,9,10,11,12,13,14,15,16 };` is your pool of numbers, **then** `int MyRandomNumber = NumbersPool[rand() % NumbersPool.size()];` is a random number out of that pool. – Khalil Khalaf Jul 26 '16 at 20:44
  • 1
    @FirstStep another fun trick is what you've got plus [std::random_shuffle](http://en.cppreference.com/w/cpp/algorithm/random_shuffle). Very helpful in cases where you don't want repetition: Just copy and and remove the first element until the pool is empty. – user4581301 Jul 26 '16 at 20:50
  • @user4581301 right ! It is so much fun that I forgot to ask or take care of duplicates.. Speaking about duplicates, the Q is marked as duplicate so next Q lol – Khalil Khalaf Jul 26 '16 at 20:53
  • Anyway, the dupe is not correct, voting to reopen. Unless I'm reading this wrong, I think LogicStuff's comment has the right solution for this one. – user4581301 Jul 26 '16 at 21:14

1 Answers1

3

here's a simple solution with a 50% chance that it's in either interval:

if (rand() % 2){
    return rand() % 4 + 1;
} else {
    return rand() % 8 + 8;
}

Otherwise, if you want the distribution to be weighted to the size of the intervals:

int num = rand() % 12 + 1;
if (num >= 4) num += 4;
return num;
alter_igel
  • 6,899
  • 3
  • 21
  • 40
  • Won't this give the exact same number the first time the program is run? – Arnav Borborah Jul 26 '16 at 21:01
  • Perhaps. I didn't write this as a full program but as a function body. In the context of a larger application, the random number function should be seeded properly. – alter_igel Jul 26 '16 at 21:05