Generating random numbers

Is it possible to generate random numbers not within a range? Like just generating a random number from 7 9 10 and 11?
C++ doesn't offer this by default. Although it isn't too hard to create yourself though. Creating a simple lookup table is all you need to do to convert the values. For example, say we use the rand() function for generating random numbers (the same tatic applies to the C++11 random number engines too). We could use the following code to produce either 7, 9, 10 or 11:

1
2
3
int lookup[] = {7,9,10,11};
int base = rand() % 4;
int number = lookup[base];


Now you have a random number that is one of the specified values.
@joshuatz

Yes, it is possible. Here's how I would do it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

using std::cout;
using std::endl;

int main()
{
	int RandNum[] = { 7, 9, 10, 11 }; // Put in as many different numbers, as needed for program
	int num;
	for (int x = 0; x < 15; x++)
	{
		num = rand() % 4; // We have %4 here, because there are 4 numbers in array
		// Change 4 to as many different numbers you're using in the array
		cout << RandNum[num] << endl;
	}
    return 0;
}
Topic archived. No new replies allowed.