#import <Foundation/NSArray.h>
@interface NSArray (Random)
- (id)anyOne;
@end
#import "NSArray+Random.h"
#import <objc/runtime.h>
@implementation NSArray (Random)
static char prevKey; //定义键使用的地址变了
static int random_value(void) {
static unsigned long rnd = 201008;
rnd = rnd * 1103515245UL + 12345;
return (int)((rnd >> 16) & 0x7fff);
}
- (id)anyOne
{
id item;
NSUInteger count = [self count];
if (count == 0)
return nil;
if (count == 1)
item = [self lastObject];
else {
id prev = objc_getAssociatedObject(self, &prevKey);
NSUInteger index = random_value() % count;
item = [self objectAtIndex:index];
if (item == prev) {
if (++index >= count)
index = 0;
item = [self objectAtIndex:index];
}
}
objc_setAssociatedObject(self, &prevKey, item, OBJC_ASSOCIATION_RETAIN);
return item;
}
@end
#import <Foundation/Foundation.h>
#import "NSArray+Random.h"
int main(void)
{
@autoreleasepool {
id arr1 = [NSArray arrayWithObjects:@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", nil];
id arr2 = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", @"4", nil];
for (int i = 5; i < 20; i++) {
@autoreleasepool {
printf("%s %s\n",[[arr1 anyOne] UTF8String], [[arr2 anyOne] UTF8String]);
}
}
}
return 0;
}