Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Random Numbers with Fixed Digits Length?

I am generating Random Number with

int randomID = arc4random() % 3000;

But I want to generate random number with atleast 4 digits. like 1000, 2400, 1122

I want to know the code for Objective C.

like image 980
Amir iDev Avatar asked Sep 27 '13 13:09

Amir iDev


2 Answers

Please try

generate numbers :1000~9999

int randomID = arc4random() % 9000 + 1000;

generate numbers :1000~2999

int randomID = arc4random() % 2000 + 1000;
like image 126
lanbo Avatar answered Oct 29 '22 22:10

lanbo


At least four digits, right?

So you need something with flexibility:

-(NSString *)getRandomPINString:(NSInteger)length
{
    NSMutableString *returnString = [NSMutableString stringWithCapacity:length];

    NSString *numbers = @"0123456789";

    // First number cannot be 0
    [returnString appendFormat:@"%C", [numbers characterAtIndex:(arc4random() % ([numbers length]-1))+1]];

    for (int i = 1; i < length; i++)
    {
        [returnString appendFormat:@"%C", [numbers characterAtIndex:arc4random() % [numbers length]]];
    }

    return returnString;
}

and use it like so:

NSString *newPINString = [self getRandomPINString:4];
like image 30
Phil Wilson Avatar answered Oct 29 '22 21:10

Phil Wilson