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
Asked
Active
Viewed 91 times
0
-
1Just generate random index. Look at `
` facilities. – Jarod42 Dec 19 '15 at 23:31
2 Answers
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
-
-
http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful – vladon Dec 19 '15 at 23:36
-
"between 0 and vector.size()" And what happens if you will get `vector.size()` and use it as index?.. – vladon Dec 19 '15 at 23:37
-
Ok. But your answer in words contains TWO horrible errors. So, your answer is incorrect. Twice. – vladon Dec 19 '15 at 23:40
-
-
Using rand() is not an error, despite what you say. And I think it is quite clear what is meant with _between_. Have a nice day. – Ctx Dec 19 '15 at 23:43
-
Ctx, if "between" means "not including", then you again not right, you miss index 0. In any meaning your answer is not good. – vladon Dec 19 '15 at 23:46
-
-
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