8

Objective-C 随机数及数组随机取元素

 2 years ago
source link: https://www.isaced.com/post-204.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Objective-C 随机数及数组随机取元素

这里记录一下Objective-C随机数以及随机数在数组中的使用。

arc4random()

这个貌似是最好用的,听说比较精确,用起来也比较方便,不需要初始化随机种子。

0 - N-1:

int value = arc4random() % x;

1 - N:

int value = (arc4random() % N) + 1;

random()

这种属于较老式的随机数,C++中也有,需要重置随即种子,用的少,也就不详细介绍了。

CCRANDOM_0_1()

这个存在与Cocos2D中,也一起归纳到这里了。这是取0-1的随机数,

[0,5]:

float random = CCRANDOM_0_1() * 5;

数组的随机操作:

数组中随机取出三个元素:

NSArray *array = [[NSArray alloc] initWithObjects:@"A",@"B",@"C",@"D",@"E",nil];
NSMutableArray *randomArray = [[NSMutableArray alloc] init];

while ([randomArray count] < 3) {
     int r = arc4random() % [array count];
     [randomArray addObject:[array objectAtIndex:r]];
}

这种我是最先想到的方法,但是有个问题就是,可能会随机出两个相同的数,甚至三个,只是可能性很小,所以我们要排除重复性,看到有从数组中先Remove的作法,但是我觉得用NSSet也不失为一种好的方法。

NSArray *array = [[NSArray alloc] initWithObjects:@"A",@"B",@"C",@"D",@"E",nil];
NSMutableSet *randomSet = [[NSMutableSet alloc] init];

while ([randomSet count] < 3) {
    int r = arc4random() % [array count];
    [randomSet addObject:[array objectAtIndex:r]];
}
    
NSArray *randomArray = [randomSet allObjects];
NSLog(@"%@",randomArray);

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK