programing

Objective-C에서 난수 생성

showcode 2023. 4. 20. 23:23
반응형

Objective-C에서 난수 생성

저는 주로 자바 헤드로, 0에서 74 사이의 의사 난수를 생성하는 방법을 원합니다.Java에서는 다음 방법을 사용합니다.

Random.nextInt(74)

시드나 진정한 랜덤성에 대한 논의는 관심 없습니다. 단지 Objective-C에서 동일한 작업을 수행하는 방법에만 관심이 있습니다.구글을 샅샅이 뒤져봤는데, 서로 상충되는 많은 정보들이 있는 것 같아요.

를 사용해야 합니다.arc4random_uniform()기능.뛰어난 알고리즘을 사용하여rand씨도 안 놔도 돼요.

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

arc4randomman 페이지:

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))

를 사용합니다.arc4random_uniform(upper_bound)범위 내에서 랜덤 번호를 생성하는 함수입니다.다음은 0에서 73 사이의 숫자를 생성합니다.

arc4random_uniform(74)

arc4random_uniform(upper_bound)man 페이지에서 설명한 바와 같이 모듈로의 편견을 회피합니다.

arc4sq_bound()는 upper_bound보다 작은 균등하게 분산된 난수를 반환합니다.arc4pair_pair()는 "pair4pair() % upper_bound"와 같은 구성보다 권장됩니다.이는 상한이 2의 거듭제곱이 아닐 때 "modulo bias"를 피하기 때문입니다.

C와 마찬가지로 다음과 같이 할 수 있습니다.

#include <time.h>
#include <stdlib.h>
...
srand(time(NULL));
int r = rand() % 74;

(0은 포함하지만 74는 제외한다는 것을 전제로 하고 있습니다.이것이 Java의 예)

편집: 자유롭게 대체 가능random()또는arc4random()위해서rand()(다른 사람들이 지적한 바와 같이, 그것은 꽤 형편없다.)

여러 프로젝트에서 사용하는 방법을 추가할 수 있을 것 같아서요.

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

많은 파일에서 사용하게 되면 보통 매크로를 다음과 같이 선언합니다.

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

예.

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

주의: iOS 4.3/OS X v10.7(Lion) 이후에만 해당

그러면 0에서 47 사이의 부동 소수점 숫자가 표시됩니다.

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

또는 단순히

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

하한과 상한 모두 음수일 수도 있습니다.다음 예제 코드는 -35.76에서 +12.09 사이의 난수를 제공합니다.

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

결과를 동그라미 정수 값으로 변환:

int intRndValue = (int)(rndValue + 0.5);

rand(3)의 매뉴얼 페이지에 따르면 rand 함수 패밀리는 랜덤(3)에 의해 폐지되었다.이는 rand()의 하위 12비트가 순환 패턴을 통과하기 때문입니다.랜덤 번호를 얻으려면 srandom()을 부호 없는 시드로 호출하고 random()을 호출하여 제너레이터를 시드합니다.따라서 위의 코드와 동등한 것은

#import <stdlib.h>
#import <time.h>

srandom(time(NULL));
random() % 74;

시드를 변경하지 않는 한 프로그램에서 srandom()을 한 번만 호출하면 됩니다.진정한 랜덤 값에 대한 논의를 원하지 않는다고 하셨지만, rand()는 매우 나쁜 랜덤 번호 생성기이며 rand()는 0과 RAND_MAX 사이의 숫자를 생성하기 때문에 여전히 모듈로 편향에 시달리고 있습니다.따라서 예를 들어, RAND_MAX가 3이고, 0과 2 사이의 난수를 얻으려면 0이나 2보다 2배 더 높은 확률입니다.

하는 arc4random_uniformiOS 4.3 서os서 。다행히 iOS는 컴파일 시간이 아닌 런타임에 이 기호를 바인딩합니다(따라서 #if preprocessor 디렉티브를 사용하여 사용 가능 여부를 확인하지 마십시오).

「」의 유무를 판단하는 .arc4random_uniform을 사용하다

#include <stdlib.h>

int r = 0;
if (arc4random_uniform != NULL)
    r = arc4random_uniform (74);
else
    r = (arc4random() % 74);

Java의 Math.random()과 같은 기능을 하기 위해 나만의 난수 유틸리티 클래스를 작성했습니다.기능은 2개뿐이고, 모두 C로 되어 있습니다.

헤더 파일:

//Random.h
void initRandomSeed(long firstSeed);
float nextRandomFloat();

구현 파일:

//Random.m
static unsigned long seed;

void initRandomSeed(long firstSeed)
{ 
    seed = firstSeed;
}

float nextRandomFloat()
{
    return (((seed= 1664525*seed + 1013904223)>>16) / (float)0x10000);
}

이것은 의사 난수를 발생시키는 아주 전형적인 방법입니다.내 앱 위임자에서 전화:

#import "Random.h"

- (void)applicationDidFinishLaunching:(UIApplication *)application
{
    initRandomSeed( (long) [[NSDate date] timeIntervalSince1970] );
    //Do other initialization junk.
}

그리고 나서 나는 그냥 말한다:

float myRandomNumber = nextRandomFloat() * 74;

이 메서드는 0.0f(포함)에서 1.0f(포함) 사이의 난수를 반환합니다.

이미 훌륭하고 명쾌한 답이 몇 개 있지만, 이 문제는 0에서 74 사이의 난수를 요구합니다.용도:

arc4random_uniform(75)

0에서 99 사이의 난수 생성:

int x = arc4random()%100;

500에서 1000 사이의 난수를 생성합니다.

int x = (arc4random()%501) + 500;

iOS 9 및 OS X 10.11부터는 새로운 GameplayKit 클래스를 사용하여 다양한 방법으로 난수를 생성할 수 있습니다.

선택할 수 있는 소스 유형은 일반 랜덤 소스(이름 미지정, 시스템 선택 가능), 선형 합동 소스, ARC4 및 Mersenne Twister 등 4가지입니다.이것들은 랜덤 int, 플로트 및 bool을 생성할 수 있습니다.

가장 간단한 수준에서 다음과 같이 시스템에 내장된 랜덤 소스에서 랜덤 번호를 생성할 수 있습니다.

NSInteger rand = [[GKRandomSource sharedRandom] nextInt];

그러면 -2,147,483,648에서 2,147,483,647 사이의 숫자가 생성됩니다.0에서 상한(전용) 사이의 숫자를 원하는 경우 다음을 사용합니다.

NSInteger rand6 = [[GKRandomSource sharedRandom] nextIntWithUpperBound:6];

GameplayKit에는 주사위 조작을 위한 편리한 컨스트럭터가 내장되어 있습니다.예를 들어, 다음과 같이 6면 다이를 굴릴 수 있습니다.

GKRandomDistribution *d6 = [GKRandomDistribution d6];
[d6 nextInt];

이렇게 랜덤 수 있습니다.GKShuffledDistribution.

//다음 예제에서는 0 ~73의 숫자를 생성합니다.

int value;
value = (arc4random() % 74);
NSLog(@"random number: %i ", value);

//In order to generate 1 to 73, do the following:
int value1;
value1 = (arc4random() % 73) + 1;
NSLog(@"random number step 2: %i ", value1);

출력:

  • 난수: 72

  • 난수 2단계: 52

game dev의 경우 random()을 사용하여 랜덤을 생성합니다.arc4random()을 사용하는 경우보다 최소 5배 빠를 수 있습니다.모듈로 바이어스는 특히 게임에서 랜덤()의 전체 범위를 사용하여 랜덤을 생성할 때 문제가 되지 않습니다.반드시 씨를 먼저 뿌리세요.AppDelegate에서 srandomdev()를 호출합니다.도우미 기능은 다음과 같습니다.

static inline int random_range(int low, int high){ return (random()%(high-low+1))+low;}
static inline CGFloat frandom(){ return (CGFloat)random()/UINT32_C(0x7FFFFFFF);}
static inline CGFloat frandom_range(CGFloat low, CGFloat high){ return (high-low)*frandom()+low;}

언급URL : https://stackoverflow.com/questions/160890/generating-random-numbers-in-objective-c

반응형