Reputation: 85
I need to use rand()
function to get numbers between 1-15, so I simply used the function as below.
num1 = rand()%15+1;
But between this 1-15 range, there are some numbers that I want to prevent from being assigned into num1
variable.
I thought about putting an if-else
function there, as the rand()
function would repeat itself on such occasion that an undesired number turned up.
However, what I'm most curious is whether there is a more effective way to omit these undesired numbers from rand()
function's range.
Thank you so much!
Upvotes: 2
Views: 1033
Reputation: 3170
Sounds that you want to have e.g. a random number of the set { 1, 2, 3, 7, 8, 9, 14, 15 } (isn't it)?
So, for this example, this is a count of 8 different values and you can do it like this:
lookupTable[] = { 1, 2, 3, 7, 8, 9, 14, 15 };
num1 = lookupTable[rand() % 8];
I'd placed a running example here.
Upvotes: 5
Reputation: 9404
To get real random numbers between 1 and 15, you can use such C++11 code:
#include <iostream>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> dist(1, 15);
for (int i = 0; i < 100; ++i)
std::cout << dist(mt) << ", ";
}
To remove some of this number you can use map
as suggested owacoder
Also you see video (from MS guy who wrote part of VS STL) about how to get real random number, and why rand
can not be used for that:
https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful
Upvotes: 3
Reputation: 4873
A very simple solution: call rand()
with a modulo value equal to the total count of numbers in your output range. Then define a mapping function to map values into your required specific output ranges.
For example: to get a random value between 1 and 5 or 11 and 15, inclusive:
int map(int val)
{
if (val > 5)
return val+5;
else
return val;
}
int value = rand()%10+1;
value = map(value);
Upvotes: 6