Generando números aleatorios en Objective-C

Resuelto rustyshelf asked hace 15 años • 13 respuestas

Soy principalmente un experto en Java y quiero una forma de generar un número pseudoaleatorio entre 0 y 74. En Java usaría el método:

Random.nextInt(74)

No estoy interesado en una discusión sobre semillas o aleatoriedad verdadera, solo cómo se realiza la misma tarea en Objective-C. Busqué en Google y parece haber mucha información diferente y contradictoria.

rustyshelf avatar Oct 02 '08 11:10 rustyshelf
Aceptado

Deberías usar la arc4random_uniform()función. Utiliza un algoritmo superior para rand. Ni siquiera necesitas poner una semilla.

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

La arc4randompágina de manual:

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))
lajos avatar Oct 02 '2008 16:10 lajos

Utilice la arc4random_uniform(upper_bound)función para generar un número aleatorio dentro de un rango. Lo siguiente generará un número entre 0 y 73 inclusive.

arc4random_uniform(74)

arc4random_uniform(upper_bound)evita el sesgo de módulo como se describe en la página de manual:

arc4random_uniform() devolverá un número aleatorio distribuido uniformemente menor que el límite superior. arc4random_uniform() se recomienda sobre construcciones como ``arc4random() % Upper_bound'' ya que evita el " sesgo de módulo " cuando el límite superior no es una potencia de dos.

yood avatar Aug 16 '2011 17:08 yood

Pensé que podría agregar un método que uso en muchos proyectos.

- (NSInteger)randomValueBetween:(NSInteger)min and:(NSInteger)max {
    return (NSInteger)(min + arc4random_uniform(max - min + 1));
}

Si termino usándolo en muchos archivos normalmente declaro una macro como

#define RAND_FROM_TO(min, max) (min + arc4random_uniform(max - min + 1))

P.ej

NSInteger myInteger = RAND_FROM_TO(0, 74) // 0, 1, 2,..., 73, 74

Nota: Sólo para iOS 4.3/OS X v10.7 (Lion) y posteriores

Groot avatar Jun 19 '2013 14:06 Groot

Esto le dará un número de coma flotante entre 0 y 47.

float low_bound = 0;      
float high_bound = 47;
float rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);

O simplemente simplemente

float rndValue = (((float)arc4random()/0x100000000)*47);

Tanto el límite inferior como el superior también pueden ser negativos . El siguiente código de ejemplo le proporciona un número aleatorio entre -35,76 y +12,09

float low_bound = -35.76;      
float high_bound = 12.09;
float rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);

Convierta el resultado a un valor entero más redondo :

int intRndValue = (int)(rndValue + 0.5);
Tibidabo avatar Feb 16 '2012 11:02 Tibidabo