NSMutableArray Shuffle Addition

//you can shuffle any NSMutableArray with below code   

//header 
@interface NSMutableArray (Shuffle)
- (void)shuffle;
@end



//implementation 
@implementation NSMutableArray (Shuffle)
- (void)shuffle
{
    static BOOL seeded = NO;
    if(!seeded)
    {
        seeded = YES;
        //srandom is a function that initializes the random number generator.
        srandom(time(NULL));
    }
    NSUInteger count = [self count];
    for (NSUInteger i = 0; i < count; ++i) {
        int arraySize = count - i;
        int n = (random() % arraySize) + i;
        [self exchangeObjectAtIndex:i withObjectAtIndex:n];
    }
}
@end

   .....
- (void)shuffleExapmle:(id)obj {
    NSMutableArray *array=[NSMutableArray arrayWithObjects:@"item 1", @"item2 ", @"item 3", @"item 4", nil];
    [array shuffle];
    ........
    ......

No comments:

Post a Comment