5

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Amir iDev
  • 1,257
  • 2
  • 15
  • 29
  • How many time you want to generate 4 digit number ? – Dharmbir Singh Sep 27 '13 at 13:26
  • @DharmbirChoudhary I want to send it messages to server it will not kept in cache it will be clean. – Amir iDev Sep 27 '13 at 13:29
  • 1
    This question has been asked so many times. Please check this answer http://stackoverflow.com/questions/160890/generating-random-numbers-in-objective-c/7082580#7082580. You better use a solution with `arc4random_uniform` as your upper bound is 9999 or 2999. – marsei Sep 27 '13 at 13:41

2 Answers2

24

Please try

generate numbers :1000~9999

int randomID = arc4random() % 9000 + 1000;

generate numbers :1000~2999

int randomID = arc4random() % 2000 + 1000;
lanbo
  • 1,678
  • 12
  • 12
  • Suppose if random number is 3000 and add 1000 then it will be 4000. So user wanna less then 3000. So it may be problem in future. – Dharmbir Singh Sep 27 '13 at 13:33
  • 3
    if it wants less than 3000 and 4 digits then you can use int randomID = arc4random() % 2000 + 1000; – lanbo Sep 27 '13 at 13:35
8

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];
CodeChanger
  • 7,953
  • 5
  • 49
  • 80
Phil Wilson
  • 888
  • 6
  • 8