First of all, I highly recommend (if you haven't already) acquiring a C++11 (or higher) compliant compiler. It will give you access to standardized, random number generating facilities far superior to the archaic
rand
and
srand
found in
cstdlib
.
Here is an elegant function to wrap just one of the random number generating facilities.
1 2 3 4 5 6
|
int random(int min, int max) {
static std::random_device device{};
static std::default_random_engine engine{ device() };
std::uniform_int_distribution<int> distribution{ min, max };
return distribution(engine);
}
|
In the function above, std::random_device is a uniformly-distributed random number generator. It can produce non-deterministic random numbers if a non-deterministic source (e.g. hardware) is available to the implementation. Otherwise, it will generate pseudo-random numbers.
(You can check the non-deterministic property of this generator by accessing it's
entropy
member, which should be a non-zero value if a non-deterministic source is available.)
We'll be calling the
device
's constructor to supply a seed to
engine
, which is a pseudo-random number generator.
We then obtain random numbers, uniformly distributed on the interval
[min, max]
inclusive.
Regardless of which implementation you end up using, it's helpful to wrap random number generating code in a function.
Here's one possible solution to your problem:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
#include <iostream>
#include <random>
int random(int min, int max) {
static std::random_device device{};
static std::default_random_engine engine{ device() };
std::uniform_int_distribution<int> distribution{ min, max };
return distribution(engine);
}
int main() {
struct Range {
int min, max;
};
const int num_ranges = 3;
const Range ranges[num_ranges] = {
{191, 197},
{217, 218},
{32, 32}
};
Range index = ranges[random(0, num_ranges-1)];
int number = random(index.min, index.max);
std::cout << "Min:\t" << index.min << "\nMax:\t" << index.max << "\nNumber:\t" << number << std::endl;
return 0;
}
|