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;dr: Use 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
NSUInteger r = arc4random_uniform(N);
Random int between 1 and N
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).
srand48(time(0));
double r = drand48();
rand48functions, unlikearc4randomfunctions, 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.
if ([array count] > 0) {
id obj = array[arc4random_uniform([array count])];
}
How Do I Randomly Order an NSArray?
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
NSSet,NSOrderedSet, andNSDictionary.
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:
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:
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
3inside of parentheses, following the organizational convention ofmanpages.
arc4randomdoes not require an initial seed (withsrandorsrandom), making it that much easier to use.arc4randomhas a range up to0x100000000 (4294967296), whereasrandandrandomtop out atRAND_MAX = 0x7fffffff (2147483647).randhas 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?
randis a standard C function.randomis defined as part of the POSIX standard.arc4randomis provided on BSD and derived platforms.
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.
|
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); |
|
1
|
document.write(Math.random()*(n+1-m)+m); |
/// <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的更多相关文章
- iPhone开发随想:rand()还是arc4random()
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://bj007.blog.51cto.com/1701577/544006 今天在iP ...
- sql随机查询数据语句(NewID(),Rnd,Rand(),random())
SQL Server: 代码如下 复制代码 Select TOP N * From TABLE Order By NewID() NewID()函数将创建一个 uniqueidentifier 类型的 ...
- iOS中产生随机数的方法
利用arc4random_uniform()产生随机数 Objective-C 中有个arc4random()函数用来生成随机数且不需要种子,但是这个函数生成的随机数范围比较大,需要用取模的算法对随机 ...
- objective-c 中随机数的用法 3种:arc4random() 、random()、CCRANDOM_0_1()
oc 中随机数的用法(arc4random() .random().CCRANDOM_0_1() 1).arc4random() 比较精确不需要生成随即种子 使用方法 : 通过arc4random() ...
- Verilog $random用法
“$random函数调用时返回一个32位的随机数,它是一个带符号的整形数...”,并给出了一个例子: _________________________________________________ ...
- pwnable.kr random 之 write up
---恢复内容开始--- 首先看源代码: #include <stdio.h> int main(){ unsigned int random; random = rand(); // r ...
- day 5 模块导入、常用模块os shutil sys commands subprocess hashlib json pickle zipfile traceback random datetime
os: os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname") 改变当前脚本工作目录:相当于shell下cd os. ...
- reservoir sampling / random shuffle
randomly choose a sample of k items from a list S containing n elements, the algorithm may be online ...
- verilog random使用
“$random函数调用时返回一个32位的随机数,它是一个带符号的整形数...”,并给出了一个例子: _________________________________________________ ...
随机推荐
- C#基础总结
1.执行.NET应用程序时经历的几个步骤 用C#编写应用程序代码 把应用程序代码编译为中间语言代码(MSIL),存储在程序集中 使用JIT编译器将MSIL编译为本机代码 在托管的公共语言运行库(CLR ...
- 搭建一个分布式MongoDB鉴权集群
今天休假在家,测试并搭建了一个replica set shard MongoDB鉴权集群.replica set shard 鉴权集群中文资料比较少,本文是个人笔记,同时也希望对后来者有所帮助.本文仅 ...
- git clone带用户名和密码的方式
git clone http://username:password@127.0.0.1/res/res.git
- 为更好地设计数据库,重新整理sql server数据类型
我们在平常开发过程中,在设计数据的时候,经常碰到数据类型选择的问题,为了更快,更合适地选择正确的数据类型,所以在这里做个总结. 分类 sql server 数据类型 c# 数据类型 描述 应用场景 字 ...
- 对COM 组件的调用返回了错误 HRESULT E_FAIL
.net ppt转pdf时报以下错误: 对COM 组件的调用返回了错误 HRESULT E_FAIL 在服务器端打开PPT,选项--另存为--PDF,发现PowerPoint报了个错误: “无法找到打 ...
- [CentOS] 解决 crontab 无法读取环境变量的问题
参考资料:http://blog.slogra.com/post-238.html 1. 问题描述 一段数据处理的 shell 程序,在 shell 中手动运行,可以正确执行.但是,把它放在 cron ...
- DNS bind子域授权安装
失败经验:rhel 6.x bind 9.8,两台做子域授权,最后失败.原因不详. 改用rhel 5.5, bind 9.3,同样的配置,就成功了.具体记录一下9.3的配置. 安装:采用安装RHEL时 ...
- Selenium的延迟等待
http://my.oschina.net/u/928852/blog/98885 Selenium的延迟等待分为 显式等待(Explicit Wait) & 隐式等待(Implicit Wa ...
- Python - twisted web 入门学习之一
原文地址:http://zhouzhk.iteye.com/blog/765884 python的twisted框架中带了一个web server: twisted web.现在看看怎么用. 一)准备 ...
- Ubuntu安装node
#!/bin/bash echo "添加环境变量需要root权限,如无root权限,则不添加环境变量" echo "输入Node下载地址(目前仅支持Node官方网站上Li ...