The revolutionary project management tool is here! Plan visually with a single glance and make sure your projects get done.
int rand(int maxVal)
{
int x = random(maxVal);
if((x>=2)&&(x<=maxVal))
return x;
else rand(maxVal);
}
int exclude(int x,y)
{
int value = rand(120);
if((value == x)||(value == y))
value = exclude(x,y);
return value;
}
#include <cstdlib>
#include <ctime>
// calculate a random value between min and max (inclusive)
int getRand(int min, int max) {
return min + (rand() % (max - min + 1));
}
int main(void) {
srand(time(0)); // <--- call this once at the start of the application
int value = getRand(2, 120); // <--- the random value between 2 and 120 (inclusive)
return 0;
}
#include <cstdlib>
#include <ctime>
#include <set>
// calculate a random value between min and max (inclusive), without using the excluded values
int getRandExclude(int min, int max, std::set<int> excludes) {
int value = min + (rand() % (max - min + 1 - excludes.size()));
std::set<int>::const_iterator it;
for (it = excludes.begin(); it != excludes.end(); ++it) {
if (value >= *it) ++value;
else break;
}
return value;
}
int main(void) {
srand(time(0)); // <--- call this once at the start of the application
std::set<int> excl; // <--- list of values to be excluded
excl.insert(5);
excl.insert(100);
excl.insert(50);
int value = getRandExclude(2, 120, excl); // <--- the random value between 2 and 120 (inclusive) without the excluded values
return 0;
}
If you are experiencing a similar issue, please ask a related question
Join the community of 500,000 technology professionals and ask your questions.