数组随机取元素 — 不考虑重复情况
NSArray *array = [[NSArray alloc] initWithObjects:@"A",@"B",@"C",@"D",@"E",nil];
NSMutableArray *randomArray = [[NSMutableArray alloc] init];
while ([randomArray count] < 5) {
int r = arc4random() % [array count];
[randomArray addObject:[array objectAtIndex:r]];
}
NSLog(@"randomArray = %@",randomArray);
数组随机取元素 — 去除重复元素
NSArray *array = [[NSArray alloc] initWithObjects:@"A",@"B",@"C",@"D",@"E",nil];
NSMutableSet *randomSet = [[NSMutableSet alloc] init];
while ([randomSet count] < 5) {
int r = arc4random() % [array count];
[randomSet addObject:[array objectAtIndex:r]];
}
NSArray *randomArray = [randomSet allObjects];
NSLog(@"%@",randomArray);
网友评论