Reputation: 225
Is it possible to generate a random numbers between 1 -10 but it should not be 5?
Upvotes: 1
Views: 5716
Reputation: 24403
A simple solution is to generate a random number between 1-10 using a system function and if it happens to be 5 generate it again until it is not the case. This solution has a minuscule probability that your function doesn't return until the iPhone batter dies :). The alternative is listed below
Another solution is to generate a random number using a system function between 1-9 and map 5-9 as 6-10
int GenRandomNumber()
{
int x = GetSystemRandomBetween1and9();
if ( x >= 5 )
x += 1;
return x;
}
Upvotes: 2
Reputation: 212949
#include <stdlib.h>
// ...
int i;
do {
i = rand() % 10 + 1; // generate random number from 1 to 10
} while (i == 5); // repeat until number != 5
Upvotes: 6