Chuck
Chuck

Reputation: 1870

Objective-C repeatable random number generators a la java.util.Random

For testing and other purposes, it is often useful to be able to generate multiple streams of repeatable random numbers. In Java, there is java.util.Random. You can create multiple Random objects each with their own seed so that subsequent calls to any particular Random instance will return the same sequence of pseudo random numbers every time you run the program. I've seen the documentation for arc4random, which looks like a great generator. However, I don't see any way to provide a seed or anyway to support multiple independent instances. It looks like the random() family of BSD library functions is the best way to do this. Something like the following excerpt...

@interface Random : NSObject {
    @private
    char _state[256];
}

+ (Random *)getDefaultInstance;
+ (Random *)getRepeatableInstance;
- (Random *)init;
- (Random *)initWithSeed:(unsigned)seed;
- (long)nextLong;
@end

@implementation Random

- (void)setup:(unsigned)seed
{
    initstate(seed, _state, sizeof(_state));
}

- (Random *)init
{
    self = [super init];
    unsigned seed = (unsigned)arc4random();
    [self setup:seed];
    return self;
}

- (Random *)initWithSeed:(unsigned int)seed
{
    self = [super init];
    [self setup:seed];
    return self;
}

- (long)nextLong
{
    char *oldState = setstate(_state);
    long result = random();
    setstate(oldState);
    return result;
}
@end

Is there already something else that does this? I'm not concerned about thread safety. I won't use generators across threads.

Upvotes: 1

Views: 326

Answers (2)

Christian Stieber
Christian Stieber

Reputation: 12496

"Is there already something else that does this?"

It's always difficult to answer with "no" since it's difficult to argue that I know everything because I certainly don't, but no -- I've never encountered anything like that (as an Cocoa class, that is. The usecase itself is common enough).

Upvotes: 1

Sulthan
Sulthan

Reputation: 130102

What you want is called pseudo-random number generation. Some algorithms here https://mathoverflow.net/questions/29494/pseudo-random-number-generation-algorithms or more info here http://en.wikipedia.org/wiki/Random_number_generators.

Using system functions (rand(), srand(), random(), srandom() and arc4random()) is generally enough for everybody's needs.

Also note that long in obj-c is very different from long in Java.

Upvotes: 0

Related Questions