生成连续随机数序列
题目:生成含 0~99 的 100 个元素的随机序列
思路:
先生成 0 到 99 的递增数组,然后 ramdon 99 次,每次和 random 下标交换
a[random(99)] 和 a[99]交换,(给元素99随机找了一个位置)
a[random(98)] 和 a[98]交换,(给元素98随机找了一个位置)
…
a[random(1)] 和 a[1] 交换
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *a = [self p_randomArr:100];
NSLog(@"%@", a);
}
///> 生成包含 0 至 count 的不重复的随机数组
- (NSArray <NSNumber *>*)p_randomArr:(int)count {
NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:count];
for (int i=0; i<count; i++) {
[arrM addObject:@(i)];
}
for (int j=count-1; j>=1;j--) {
int ardm = arc4random() % (j+1);
int idxVardm = [arrM[ardm] intValue];
int idxVj = [arrM[j] intValue];
arrM[j] = @(idxVardm);
arrM[ardm] = @(idxVj);
}
return arrM.copy;
}