Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Generate random number without repetition in ObjectveC

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 347
    Comment on it

    This blog includes generating the random number without repetition of number in specific range.

    For this we need to take a array to store the generated number so that we can keep track that the number is already generated or not.

    Here is the code-

     

    -(void)generateRandomNumber{
        //initialize array
        arrayRandomNumber=[[NSMutableArray alloc]init];
        while (arrayRandomNumber.count<12) {
        //define the range
        NSInteger randomNumber=1+arc4random()%12;
        if (![arrayRandomNumber containsObject:[NSString stringWithFormat:@"%d",randomNumber]])       {
              [arrayRandomNumber addObject:[NSString stringWithFormat:@"%d",randomNumber]];
         }
             continue;
        }
         NSLog(@"%@",arrayRandomNumber);
    }
    

    We can define the range in the above function. e.g.- In above function - It generates random number from 1 to 12.  we can change it accordingly.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: