0

I want to generate random number from specific integers example : generate random number from these values {2,7,9,8,11,13,16} the generated number is one of these values

2 Answers2

0

The simple way is: put these values into a vector, generate a number between 0 and vector.size() using rand() and use this value as index.

Ctx
  • 18,090
  • 24
  • 36
  • 51
0

Try somethig like this:

#include <iostream>
#include <stdlib.h>
#include <time.h>

int main ()
{
  srand ( time(NULL) ); //initialize the random seed

  const int SIZE = 7;
  const int arrayNum[SIZE] = {2,7,9,8,11,13,16};
  int RandIndex = rand() % SIZE; //generates a random number between 0 and 6
  std::cout << arrayNum[RandIndex];
}

Hope it helps =)

Rudolf Manusachi
  • 2,311
  • 2
  • 19
  • 25
  • Thank you but its generate the same value every time If i want to used it in a loop ;) – mahmoud ismail Dec 19 '15 at 23:55
  • are you sure that as index you used new `rand() % SIZE` each time? `for(int i=0; i<10; i++)cout< – Rudolf Manusachi Dec 20 '15 at 00:08
  • @RudolfManusadzhyan `rand()` can generate identical numbers on each start. Common fix is call `rand()` several times after `srand`: `rand(); rand(); rand();`. You can even google it - it is used very often. That's why programmers MUST NOT use `rand()`, because it is a kind of shit. – vladon Dec 21 '15 at 11:57