C語言隨機(jī)函數(shù)rand() random() drand48()
OC隨機(jī)函數(shù)arc4random() arc4random_uniform()
rand()
// 生成m~n之間的隨機(jī)整數(shù)
-(int)randFrom:(int)m to:(int)n{
static BOOL isSranded = NO;
if (!isSranded) {
isSranded = YES;
srand((int)time(0));
}
return m + rand()%(n - m + 1);
}
random()
// 生成m~n之間的隨機(jī)整數(shù)
-(int)randomFrom:(int)m to:(int)n{
static BOOL isSranded = NO;
if (!isSranded) {
isSranded = YES;
srandom((int)time(0));
}
return m + random()%(n - m + 1);
}
drand48()
// 生成0~1之間的隨機(jī)浮點數(shù)
-(double)drand0To1{
static BOOL isSranded = NO;
if (!isSranded) {
isSranded = YES;
srand48(time(0));
}
return drand48();
}
arc4random()
// 生成m~n之間的隨機(jī)整數(shù)
-(int)arc4randomFrom:(int)m to:(int)n{
return m + arc4random()%(n - m + 1);
}
rac4random_uniform(int upper_bound)
// 生成0~N之間的隨機(jī)整數(shù)
-(NSInteger)randomN:(int)n{
return arc4random_uniform(n+1);
}
// 生成1~N之間的隨機(jī)整數(shù)
-(NSInteger)random1ToN:(int)n{
return arc4random_uniform(n) + 1;
}
實例應(yīng)用
// 獲取數(shù)組中隨機(jī)的一個元素
-(id)randomArrayObject:(NSArray *)array{
if ([array isKindOfClass:[NSArray class]] && [array count] > 0) {
return array[arc4random_uniform((int)array.count)];
}
return nil;
}
// 獲取1~100之間的不重復(fù)的長度是10的隨機(jī)整數(shù)數(shù)組
-(NSArray *)getRandomArray
{
NSMutableArray *seedsArray=[NSMutableArray array];
for (int i = 0 ; i < 100; i++) {
[seedsArray addObject:@(i+1)];
}
NSMutableArray *resultArray=[NSMutableArray array];
NSInteger n = 10;
for (int i = 0; i < n; i++) {
int m = arc4random_uniform((int)seedsArray.count);
[resultArray addObject:seedsArray[m]];
[seedsArray removeObjectAtIndex:m];
}
return resultArray;
}
// 隨機(jī)排序數(shù)組
-(NSArray *)randomSortArray:(NSArray *)array{
NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:array];
NSUInteger count = [mutableArray count];
if (count > 1) {
for (NSUInteger i = count - 1; i > 0; --i) {
[mutableArray exchangeObjectAtIndex:i withObjectAtIndex:arc4random_uniform((int32_t)(i + 1))];
}
}
return [NSArray arrayWithArray:mutableArray];
}