rand & random & arc4random

rand(3) / random(3) / arc4random(3) / et al.

Written by Mattt Thompson on August 12th, 2013

What passes for randomness is merely a hidden chain of causality.

In a mechanical universe of material interactions expressed through mathematical equations, it is unclear whether nature encodes an element of chance, or if it‘s a uniquely human way to reconcile uncertainty.

We can be sure of one thing, however: in the closed, digital universe of CPU cycles, processes, and threads, there is no true randomness, only pseudorandomness.

Pseudorandomness, is often implemented in a way very similar to a cryptographic hash, as a deterministic function that returns a value based on the current time (salted, of course, by some initial seed value). Also like hash functions, there are a number of PRNG, or pseudorandom number generators, each of which are optimized for particular performance characteristics: uniformity, periodicity, and computational complexity.

Of course, for app developers, all of this is an academic exercise. And rather than bore you with any more high-minded, long-winded treatises on the philosophical nature of randomness, we‘re going to tackle this one FAQ-style.

Our goal this week: to clear up all of the lingering questions and misunderstandings about doing random things in Objective-C. Let‘s dive in!


How Do I Generate a Random Number in Objective-C?

tl;drUse arc4random() and its related functions.

Specifically, to generate a random number between 0 and N - 1, use arc4random_uniform(), which avoids modulo bias.

Random int between 0 and N - 1

Objective-C

NSUInteger r = arc4random_uniform(N);

Random int between 1 and N

Objective-C

NSUInteger r = arc4random_uniform(N) + 1;

Random double between 0 and 1

If you are generating a random double or float, another good option is the more obscure rand48family of functions, including drand48(3).

Objective-C

srand48(time(0));
double r = drand48();

rand48 functions, unlike arc4random functions, require an initial value to be seeded before generating random numbers. This seed function, srand48(3), should only be run once.

How Do I Pick a Random Element from an NSArray?

Use arc4random_uniform(3) to generate a random number in the range of a non-empty array.

Objective-C

if ([array count] > 0) {
  id obj = array[arc4random_uniform([array count])];
}

How Do I Randomly Order an NSArray?

Objective-C

NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:array];
NSUInteger count = [mutableArray count];
// See http://en.wikipedia.org/wiki/Fisher–Yates_shuffle
if (count > 1) {
  for (NSUInteger i = count - 1; i > 0; --i) {
      [mutableArray exchangeObjectAtIndex:i withObjectAtIndex:arc4random_uniform((int32_t)(i + 1))];
  }
}

NSArray *randomArray = [NSArray arrayWithArray:mutableArray];

This code is borrowed from TTTRandomizedEnumerator, which also provides randomized enumerators for NSSetNSOrderedSet, and NSDictionary.

How Do I Generate a Random String?

If you‘re looking to generate "lorem ipsum"-style sentences, try constructing a Markov Chain from a corpus.

Otherwise, if you‘re looking to just get random letters, try one of the following methods:

Generate a Random Lowercase NSString

If you are operating on a known, contiguous range of Unicode characters, such as the lowercase letters (U+0061 — U+007A), you can do a simple conversion from a char:

Objective-C

NSString *letter = [NSString stringWithFormat:@"%c", arc4random_uniform(26) + ‘a‘];

Pick a Random Character From an NSString

Otherwise, a simple way to pick random letters from a set of your choosing is to simply create a string containing all of the possible letters:

Objective-C

NSString *vowels = @"aeiouy";
NSString *letter = [vowels substringWithRange:NSMakeRange(arc4random_uniform([vowels length]), 1)];

Why Should I Use arc4random(3) instead of rand(3) or random(3)?

C functions are typically denoted with a number 3 inside of parentheses, following the organizational convention of man pages.

  • arc4random does not require an initial seed (with srand or srandom), making it that much easier to use.
  • arc4random has a range up to 0x100000000 (4294967296), whereas rand and random top out at RAND_MAX = 0x7fffffff (2147483647).
  • rand has often been implemented in a way that regularly cycles low bits, making it more predictable.

What are rand(3)random(3), and arc4random(3), and Where Do They Come From?



If you have any additional questions about randomness on Objective-C, feel free to tweet @NSHipster. As always, corrections are welcome in the form of a pull request.

时间: 2024-10-16 20:57:48

rand & random & arc4random的相关文章

sql随机查询数据语句(NewID(),Rnd,Rand(),random())

SQL Server: 代码如下 复制代码 Select TOP N * From TABLE Order By NewID() NewID()函数将创建一个 uniqueidentifier 类型的唯一值.上面的语句实现效果是从Table中随机读取N条记录. Access: 代码如下 复制代码 Select TOP N * From TABLE Order By Rnd(ID) Rnd(ID) 其中的ID是自动编号字段,可以利用其他任何数值来完成,比如用姓名字段(UserName) Se(ww

reservoir sampling / random shuffle

randomly choose a sample of k items from a list S containing n elements, the algorithm may be online (i.e. the input list is unknown beforehand) https://en.wikipedia.org/wiki/Reservoir_sampling ReserviorSampling(Source[1..n], Result[1..k]) { for (int

pwnable.kr第六题:random

0x000打开环境查看源码 #include int main(){ unsigned int random; random = rand(); // random value! unsigned int key=0; scanf("%d", &key); if( (key ^ random) == 0xdeadbeef ){ printf("Good!\n"); system("/bin/cat flag"); return 0; }

swift 随机生成背景颜色

swift是一门新语言,相关的文档资料现在基本上还不是很完整.在尝试开发过程中,走了不少弯路.在这里记录一下自己的”路“,希望以后能少走弯路. 生成随机背景颜色使用的语法和C#或者JAVA基本一致. UIView.backgroundColor = UIColor 其中UIView是在设备上显示出来的从UIView继承到的对象,都会有这个属性. 其属性值是UIColor对象,而UIColor对象的构造函数有: init(white: CGFloat, alpha: CGFloat) init(h

动手动脑 自信成就人生之课后作业

?动手动脑一 请看以下代码: 上述代码可以顺利通过编译,并且输出一个“很奇怪”的结果: Ljava.lang.Object;@ba8a1dc 为什么会这样? 解释:java的object数组不能转化成string数组,在转换出错时,首先要观察被转换的对象原来是什么类型,或解开多层的包装,直到获取对象的最终类型,然后把不能再分解的类型转换成自己目标类型的对象...(稍微能理解) ?动手动脑二 随机生成10个数,填充一个数组,然后用消息框显示数组内容,接着计算数组元素的和,将结果也显示在消息框中.

IOS总结(学习过程中整理的笔记)

MVC模式:(model+view+controller):是一种帮你把代码功能和显示划分出来的设计模式: model:较为底层的数据引擎,负责管理实体中所继承的数据: view:和用户交互界面: controller:连接二者的桥梁: cocoa frameworks 有两个框架: foundation foundation  是cocoa中最基本的一些类:再mac应用程序中负责对象管理,内存管理,容器等相关数据: uikit: uikit:为程序提供可视化的底层构架,包括窗口,视图,控件类和

数组的几种排序方式

// 1.使用NSComparator排序 { // 产生随机数 NSMutableArray *unsortDataM = [NSMutableArray array]; for (NSInteger index = 0; index < 20; index++) { int random = arc4random()%20; [unsortDataM addObject:@(random)]; } NSLog(@"使用NSComparator排序前的数据:%@",unsort

pwnable.kr-random-Writeup

MarkdownPad Document html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label

跟王老师学Java三大特性(二):案例 QuickHit:游戏输出字符串

案例 QuickHit:游戏输出字符串 主讲教师:王少华   QQ群号:483773664 学习目标 完成游戏输出字符串 一.需求说明 在控制台输出随机字符串 二.思路分析 生成字符串 输出字符串 返回字符串 三.难点提示 Game类中的player属性,代表玩家,查询player的级别号,根据级别号到LevelParam类中获取该级别的字符串长度 字符串长度固定可以通过for循环来实现,而随机内容可以通过获取随机数,而不同随机数对应不同字符来实现 四.参考代码 1 2 3 4 5 6 7 8