NoviceDeveloper
NoviceDeveloper

Reputation: 225

How to generate random numbers between 1-10?

Is it possible to generate a random numbers between 1 -10 but it should not be 5?

Upvotes: 1

Views: 5716

Answers (3)

parapura rajkumar
parapura rajkumar

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

Kevin
Kevin

Reputation: 56059

int x = arc4random()%9;
x += x>=4? 2 : 1

Upvotes: 6

Paul R
Paul R

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

Related Questions