Search code examples
iphoneobjective-csrand

Creating and managing two independent random number sequences


I'm having trouble generating two independent random sequences using the rand and srand functions. The details are below, any help would be most appreciated.

I'm working on a puzzle game for the iPhone, and usually for the random number generation I use the arc4 function. However for the multiplayer mode I want both players to have the same pieces throughout the game, and the only way I can control it is to have two repeatable random sequences. If I then send the seeds to the other device, the games will be identical. However when I use rand and srand and try to switch to the other seed, the sequence starts from scratch, I somehow have to initialize two independent sequences generated with a seed.

Thank you for your responses


Solution

  • Thank you for the suggestions, this is how I implemented the whole thing. I created a singleton class with 2 instance variables - seed1 and seed2 - anytime I want to get a number from the first generator I use the method generator1, same for generator2 method. The seed1/2 is instantly set to a newly generated number every time so I can just continue where I left off. In conlusion, Josh Caswell gave me all the information I needed. Check out the code if you ever need something like this. The object inits with seeds 1 and 1 but during the game they get replaced with some other numbers that both devices share.

    @implementation RandomNumberGenerator
    
    @synthesize seed1,seed2;
    
    static RandomNumberGenerator *sharedGenerator = nil;
    
    +(RandomNumberGenerator *) sharedInstance
    {
    if(!sharedGenerator) {
        sharedGenerator = [[RandomNumberGenerator alloc] initWithSeed1:1 andSeed2:1];
    }
    
    return sharedGenerator;
    }
    
    -(id) initWithSeed1:(int) seedOne andSeed2:(int) seedTwo{
    self = [super init];
    if (self)
    {
        seed1 = seedOne;
        seed2 = seedTwo;
    }
    return self;
    }
    
    -(int) generator1{
    srand(seed1);
    int j = rand();
    seed1 = j;
    return abs(j);
    
    }
    
    -(int) generator2 {
    srand(seed2);
    int k = rand();
    seed2 = k;
    return abs(k);
    }
    
    -(int) giveRandom {
    //return abs(arc4random());
    return abs(arc4random());
    }
    
    
    @end