#import <Foundation/Foundation.h>

@interface NSMutableArray (Canfield)

- (void)shuffle;
- (void)reverse;

@end
@implementation NSMutableArray (Canfield)

/*
 * Shuffle the contents of the array---see More Programming Pearls, p. 142.
 */
- (void)shuffle
{
    unsigned i, j;
    unsigned count = [self count];
    
    srandomdev();
    for (i = count - 1; i > 0; i--) {
	j = random() % count;
	[self exchangeObjectAtIndex:i withObjectAtIndex:j];
    }
}

- (void)reverse
{
    unsigned count = [self count];
    
    if (count < 2) return;
    
    unsigned i, n = count / 2;
    unsigned maxi = count - 1;
    
    for (i = 0; i < n; i++)
	[self exchangeObjectAtIndex:i withObjectAtIndex:(maxi - i)];

}

@end

main()
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSMutableArray *a = [[NSMutableArray alloc] init];

    [a addObject:[NSNumber numberWithInt:0]];
    [a addObject:[NSNumber numberWithInt:1]];
    [a addObject:[NSNumber numberWithInt:2]];
    [a addObject:[NSNumber numberWithInt:3]];
//    [a addObject:[NSNumber numberWithInt:4]];

    NSLog(@"%@", a);
    [a reverse];
    NSLog(@"%@", a);
    [a shuffle];
    NSLog(@"%@", a);

    [pool release];
}
