Follow by Email

Search This Blog

Friday, 20 December 2013

How to Shuffle the Array

Hello friends!

Here is the very simple and easy example to shuffle array  values
here we go!
Just copy and paste in your .m file

 >>randomNo is NSMutableArray
>>ran is int value
>>
//random shuffle generate start


static NSUInteger random_below(NSUInteger n)
{
    int ran;
    ran = 1+ arc4random() % 5;
    //NSLog(@"random>>>%i",ran);
    NSUInteger m = ran;
    
    // Compute smallest power of two greater than n.
    // There's probably a faster solution than this loop, but bit-twiddling
    // isn't my specialty.
    do {
        m <<= 1;
    } while(m < n);
    
    NSUInteger ret;
    
    do {
        ret = random() % m;
    } while(ret >= n);
    
    return ret;
}


- (void)shuffle {
    for(NSUInteger i = [randomNo count]; i > 1; i--) {
        NSUInteger j = random_below(i);
        [randomNo exchangeObjectAtIndex:i-1 withObjectAtIndex:j];
    }
    NSLog(@"this is shuffle array %@",randomNo);

}


//random shuffle  generat end


1 comment: