How to generate random numbers between 1-10?
-
27-10-2019 - |
Question
Is it possible to generate a random numbers between 1 -10 but it should not be 5?
Solution
#include <stdlib.h>
// ...
int i;
do {
i = rand() % 10 + 1; // generate random number from 1 to 10
} while (i == 5); // repeat until number != 5
OTHER TIPS
int x = arc4random()%9;
x += x>=4? 2 : 1
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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow