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.


JavaScript Math.random() 函数
返回指定范围的随机数(m-n之间)的公式 [1]  :
1
2
Math.random()*(n-m)+m;
改正公式:Math.random()*(n+1-m)+m
1
document.write(Math.random());
返回随机数
1
document.write(Math.random()*(20-10)+10);
返回10-20的随机数
1
document.write(Math.random()*(n+1-m)+m);
返回指定范围的随机数(m-n之间)的公式 [1] 
 

/// <summary>
/// 获取指定区间的随机数
/// </summary>
/// <param name="min">The minimum.</param>
/// <param name="max">The maximum.</param>
/// <returns></returns>
public static int GetRandom(int min = , int max = )
{
return new Random(GetRandomSeed()).Next(min, max+);
} /// <summary>
/// 加密随机数生成器 生成随机种子
/// </summary>
/// <returns></returns>
public static int GetRandomSeed()
{ byte[] bytes = new byte[]; System.Security.Cryptography.RNGCryptoServiceProvider r = new System.Security.Cryptography.RNGCryptoServiceProvider(); r.GetBytes(bytes); return BitConverter.ToInt32(bytes, ); }

rand & random & arc4random的更多相关文章

  1. iPhone开发随想:rand()还是arc4random()

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://bj007.blog.51cto.com/1701577/544006 今天在iP ...

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

    SQL Server: 代码如下 复制代码 Select TOP N * From TABLE Order By NewID() NewID()函数将创建一个 uniqueidentifier 类型的 ...

  3. iOS中产生随机数的方法

    利用arc4random_uniform()产生随机数 Objective-C 中有个arc4random()函数用来生成随机数且不需要种子,但是这个函数生成的随机数范围比较大,需要用取模的算法对随机 ...

  4. objective-c 中随机数的用法 3种:arc4random() 、random()、CCRANDOM_0_1()

    oc 中随机数的用法(arc4random() .random().CCRANDOM_0_1() 1).arc4random() 比较精确不需要生成随即种子 使用方法 : 通过arc4random() ...

  5. Verilog $random用法

    “$random函数调用时返回一个32位的随机数,它是一个带符号的整形数...”,并给出了一个例子: _________________________________________________ ...

  6. pwnable.kr random 之 write up

    ---恢复内容开始--- 首先看源代码: #include <stdio.h> int main(){ unsigned int random; random = rand(); // r ...

  7. day 5 模块导入、常用模块os shutil sys commands subprocess hashlib json pickle zipfile traceback random datetime

    os: os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname") 改变当前脚本工作目录:相当于shell下cd os. ...

  8. reservoir sampling / random shuffle

    randomly choose a sample of k items from a list S containing n elements, the algorithm may be online ...

  9. verilog random使用

    “$random函数调用时返回一个32位的随机数,它是一个带符号的整形数...”,并给出了一个例子: _________________________________________________ ...

随机推荐

  1. Spring AOP基本概念

    Spring AOP基本概念 目录 Spring AOP定义 AOP基本术语 通知类型 AOP定义 AOP基本术语 切面( Aspect ):一个能横切多个对象的模块化的关注点.对Spring AOP ...

  2. curl --connect-timeout 判断国内外网络windows 批处理

    1.下载编译curl curl 下载地址:http://curl.haxx.se/download.html ,下载后解压到一个目录,使用vs开发者工具里的 “Visual Studio 命令提示(2 ...

  3. tweenmax.js 文档

    TweenMax 参考http://bbs.9ria.com/thread-214959-1-1.html TweenMax 可能是很多人都用的,包括我 但 是最近发现大量的运用就总会产生这样或那样的 ...

  4. .net 附加W3wp进程

    步骤:1.鼠标右键点击application项目中的web,找到属性 2.修改web服务器地址(如果使用localhost报错,则http://电脑IP/): 3.在本地iis中找到你部署的网站,点击 ...

  5. mysql 找回密码方法

    1.首先确认服务器出于安全的状态,也就是没有人能够任意地连接MySQL数据库. 因为在重新设置MySQL的root密码的期间,MySQL数据库完全出于没有密码保护的 状态下,其他的用户也可以任意地登录 ...

  6. Coding源码学习第四部分(Masonry介绍与使用(三))

    接上篇继续进行Masonry 的学习. (12)tableViewCell 布局 #import "TableViewController.h" #import "Tes ...

  7. 百度echarts地图扩展动态加载geoCoord

    var data={}; for(var i=0;i<result.length;i++){ data[(""+result[i].name+"")]=e ...

  8. ajax里面success函数return上层接收不到

    开发一个小功能,在success fail里直接return,没有收到返回值.排查,查了下往上的博客,参考了以下三个: http://blog.csdn.net/fairyhawk/article/d ...

  9. gdb调试报错记录

    警告信息: incompatible implicit declaration of built-in function ‘strlen’ [enabled by default] 原因:未添加< ...

  10. JavaScript由浅入深(一)——类型、值和变量

      JavaScript是一门面向web的.高端的.动态的.弱类型的编程语言,是学习web前端开发必备的基础技能之一.JavaScript最初是一门脚本语言(scripting-language),它 ...