# iOS-关于随机数总结rand()random()drand48()arc4random()rac4random_uniform(int upper_bound)实例应用

C语言随机函数rand() random() drand48() OC随机函数arc4random() arc4random_uniform()

# rand()

// 生成m~n之间的随机整数
-(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之间的随机整数
-(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之间的随机浮点数
-(double)drand0To1{
static BOOL isSranded = NO;
if (!isSranded) {
isSranded = YES;
srand48(time(0));
}
return drand48();
}

# arc4random()

// 生成m~n之间的随机整数
-(int)arc4randomFrom:(int)m to:(int)n{
return m + arc4random()%(n - m + 1);
}

# rac4random_uniform(int upper_bound)

// 生成0~N之间的随机整数
-(NSInteger)randomN:(int)n{
return arc4random_uniform(n+1);
}

// 生成1~N之间的随机整数
-(NSInteger)random1ToN:(int)n{
return arc4random_uniform(n) + 1;
}

# 实例应用

// 获取数组中随机的一个元素
-(id)randomArrayObject:(NSArray *)array{
if ([array isKindOfClass:[NSArray class]] && [array count] > 0) {
return array[arc4random_uniform((int)array.count)];
}
return nil;
}

// 获取1~100之间的不重复的长度是10的随机整数数组
-(NSArray *)getRandomArray
{
NSMutableArray *seedsArray=[NSMutableArray array];
for (int i = 0 ; i < 100; i++) {
}
NSMutableArray *resultArray=[NSMutableArray array];

NSInteger n = 10;
for (int i = 0; i < n; i++) {
int m = arc4random_uniform((int)seedsArray.count);
[seedsArray removeObjectAtIndex:m];
}
return resultArray;
}

// 随机排序数组
-(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];
}

31 篇文章30 人订阅

0 条评论

## 相关文章

2608

### pgsql GIS 将线段等分，均分，为点 st_lineinterpolatepoint

geometry ST_LineInterpolatePoint(geometry a_linestring, float8 a_fraction);

1542

1602

### 用RNN构建文本生成器（TensorFlow Eager+ tf.keras）

【导读】本文翻译自TensorFlow官网新出的教程《Text generation using a RNN with eager execution》，该教程...

5243

3209

2542

### 线性同余同余方程组解法（excrt）

【问题描述】 求关于 x 的同余方程组 x%a 1 =b 1  a1=b1 x%a 2 =b 2  a2=b2 x%a 3 =b 3  a3=b3 x%a...

6089

3138

### poj-1005-l tanink i need a houseboat

Fred Mapper is considering purchasing some land in Louisiana to build his house ...

882

4577