在 Objective-C 中生成随机数 [英] Generating random numbers in Objective-C

查看:40
本文介绍了在 Objective-C 中生成随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我主要是一个 Java 负责人,我想要一种生成 0 到 74 之间的伪随机数的方法.在 Java 中,我会使用该方法:

Random.nextInt(74)

我对关于种子或真正随机性的讨论不感兴趣,只对你如何在 Objective-C 中完成相同的任务感兴趣.我在谷歌上搜索过,似乎有很多不同且相互矛盾的信息.

解决方案

您应该使用 arc4random_uniform() 函数.它使用优于 rand 的算法.您甚至不需要设置种子.

#include //...//...int r = arc4random_uniform(74);

arc4random 手册页:

<块引用>

NAMEarc4random, arc4random_stir, arc4random_addrandom -- arc4 随机数生成器图书馆标准 C 库 (libc, -lc)概要#include u_int32_tarc4random(void);空白arc4random_stir(void);空白arc4random_addrandom(无符号字符*dat,int datlen);描述arc4random() 函数使用 arc4 密码使用的密钥流生成器,它使用 8*8 8位 S 盒.S-Box 可以处于大约 (2**1700) 状态.arc4random() 函数返回伪0 到 (2**32)-1 范围内的随机数,因此具有 rand(3) 和随机(3).arc4random_stir() 函数从/dev/urandom 读取数据并使用它来置换 S-Boxesarc4random_addrandom().在使用 arc4random() 之前不需要调用 arc4random_stir(),因为 arc4random() 会自动初始化自己.例子以下内容使用以下方法替代了传统的 rand() 和 random() 函数arc4random():#define foo4random() (arc4random() % ((unsigned)RAND_MAX + 1))

I'm a Java head mainly, and I want a way to generate a pseudo-random number between 0 and 74. In Java I would use the method:

Random.nextInt(74)

I'm not interested in a discussion about seeds or true randomness, just how you accomplish the same task in Objective-C. I've scoured Google, and there just seems to be lots of different and conflicting bits of information.

解决方案

You should use the arc4random_uniform() function. It uses a superior algorithm to rand. You don't even need to set a seed.

#include <stdlib.h>
// ...
// ...
int r = arc4random_uniform(74);

The arc4random man page:

NAME
     arc4random, arc4random_stir, arc4random_addrandom -- arc4 random number generator

LIBRARY
     Standard C Library (libc, -lc)

SYNOPSIS
     #include <stdlib.h>

     u_int32_t
     arc4random(void);

     void
     arc4random_stir(void);

     void
     arc4random_addrandom(unsigned char *dat, int datlen);

DESCRIPTION
     The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8
     bit S-Boxes.  The S-Boxes can be in about (2**1700) states.  The arc4random() function returns pseudo-
     random numbers in the range of 0 to (2**32)-1, and therefore has twice the range of rand(3) and
     random(3).

     The arc4random_stir() function reads data from /dev/urandom and uses it to permute the S-Boxes via
     arc4random_addrandom().

     There is no need to call arc4random_stir() before using arc4random(), since arc4random() automatically
     initializes itself.

EXAMPLES
     The following produces a drop-in replacement for the traditional rand() and random() functions using
     arc4random():

           #define foo4random() (arc4random() % ((unsigned)RAND_MAX + 1))

这篇关于在 Objective-C 中生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆