shubbbik
shubbbik

Reputation: 29

Can I specify conditions for the rand() function?

I want to generate a random number that will be in the range of 1 to 6 (I know how to do that) but won't be equal to 4 other variables (for instance, their names are "num1", "num2", "num3" and "num4") in the algorithm. Can I do that? and how?

Upvotes: 1

Views: 349

Answers (1)

Clifford
Clifford

Reputation: 93476

It is not (currently) clear in the question, but from the clarification in the comments:

You want four variables, each with a random value between 1 and 6 (inclusive), but no repeats?

Assuming in fact you need 5 variables because the question states:

won't be equal to 4 other variables

then since you need 5 unique variables from 6 possibilities. The simplest solution then is to pick at random just one of the possibilities to omit. Furthermore the sensible means of storing 5 values of the same type is to use a single array variable rather then five separate variables - it makes the code far simpler.

int num[5] ;
int omit = 1 + rand() % 6 ;
for( int i = 0, j = 0; i < sizeof(num) / sizeof(*num); i++, j++ )
{
    if( i != omit ) num[j] = i ;
}

Note that the expression 1 + rand() % 6 will have a bias for some values even if rand() were entirely random. An exercise for the reader if that is an issue.

Upvotes: 3

Related Questions