code

NSArray에서 임의의 개체 선택

codestyles 2020. 9. 23. 07:38
반응형

NSArray에서 임의의 개체 선택


객체 1, 2, 3 및 4 가있는 배열이 있다고 가정 해 보겠습니다. 이 배열에서 임의의 객체를 어떻게 선택합니까?


@Darryl의 대답은 정확하지만 약간의 조정을 사용할 수 있습니다.

NSUInteger randomIndex = arc4random() % theArray.count;

수정 :

  • arc4random()over rand()and 사용 random()은 시드 ( srand()또는 호출 srandom())가 필요하지 않기 때문에 더 간단합니다 .
  • 모듈로 연산자는 ( %또한 의미 명확하면서), 전체 문 짧은합니다.

이것이 제가 생각해 낼 수있는 가장 간단한 해결책입니다.

id object = array.count == 0 ? nil : array[arc4random_uniform(array.count)];

그것은 확인하는 것이 필요 count비 때문에 nil하지만 비어 NSArray반환 0을 위해 count, 그리고 arc4random_uniform(0)돌아갑니다 0. 따라서 확인하지 않으면 배열의 경계를 벗어납니다.

이 솔루션은 유혹적이지만 빈 배열로 인해 충돌이 발생하기 때문에 잘못 되었습니다.

id object = array[arc4random_uniform(array.count)];

참고로 다음은 문서입니다 .

u_int32_t
arc4random_uniform(u_int32_t upper_bound);

arc4random_uniform() will return a uniformly distributed random number less than upper_bound.

남자 페이지는 언급하지 않는 arc4random_uniform반환 0하는 경우 0로 전달됩니다 upper_bound.

또한에 arc4random_uniform정의되어 <stdlib.h>있지만 #importiOS 테스트 프로그램 에서는을 추가 할 필요가 없습니다.


아마도 다음과 같은 내용 일 것입니다.

NSUInteger randomIndex = (NSUInteger)floor(random()/RAND_MAX * [theArray count]);

난수 생성기를 초기화하는 것을 잊지 마십시오 (예 : srandomdev ()).

참고 : 아래 답변에 따라 점 구문 대신 -count를 사용하도록 업데이트했습니다.


@interface NSArray<ObjectType>  (Random)
- (nullable ObjectType)randomObject;
@end

@implementation NSArray (Random)

- (nullable id)randomObject
{
    id randomObject = [self count] ? self[arc4random_uniform((u_int32_t)[self count])] : nil;
    return randomObject;
}

@end

편집 : Xcode 7에 대해 업데이트되었습니다. Generics, nullability


난수를 생성하여 색인으로 사용합니다. 예:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        NSArray *array = [NSArray arrayWithObjects: @"one", @"two", @"three", @"four", nil];
        NSUInteger randomNumber;
        int fd = open("/dev/random", O_RDONLY);
        if (fd != -1) {
            read(fd, &randomNumber, sizeof(randomNumber));
            close(fd);
        } else {
            fprintf(stderr, "Unable to open /dev/random: %s\n", strerror(errno));
            return -1;
        }
        double scaledRandomNumber = ((double)randomNumber)/NSUIntegerMax * [array count];
        NSUInteger randomIndex = (NSUInteger)floor(scaledRandomNumber);
        NSLog(@"random element: %@", [array objectAtIndex: randomIndex]);
    }
    return 0;
}

 srand([[NSDate date]  timeIntervalSince1970]);

 int inx =rand()%[array count];

inx는 난수입니다.

where srand() can be anywhere in the program before the random picking function.


ObjectType *objectVarName = [array objectAtIndex:arc4random_uniform((int)(array.count - 1))];

if you want to cast that to an int, here's the solution for that (useful for when you need a random int from an array of non-sequential numbers, in the case of randomizing an enum call, etc)

int intVarName = (int)[(NSNumber *)[array objectAtIndex:arc4random_uniform((int)(array.count - 1))] integerValue];

In Swift 4:

let array = ["one","two","three","four"]
let randomNumber = arc4random_uniform(UInt32(array.count))

array[Int(randomNumber)]

참고URL : https://stackoverflow.com/questions/3318902/picking-a-random-object-in-an-nsarray

반응형