Tuesday, 16 October 2012

Randomize the nsmutablearray + iphone

- (void)shuffle{
    static BOOL seeded = NO;
    if(!seeded)    {
        seeded = YES;
        srandom(time(NULL));
    }
    for (int i = 0; i < [cardsArray count]; ++i) {
        //Select a random element between i and end of array to swap with.
        int nElements = [cardsArray count]-i;
        int n = (random() % nElements) + i;
        [cardsArray exchangeObjectAtIndex:i withObjectAtIndex:n];
    }
    NSLog(@"%@",cardsArray);
}

http://stackoverflow.com/questions/56648/whats-the-best-way-to-shuffle-an-nsmutablearray

No comments:

Post a Comment