How do I seed the random generator and create a ra

2019-07-04 02:46发布

I have seen some examples of the random int in Objective-C, but all people are complaining about the same number sequence every time the application runs. I have read about seeding the random number, but I am not sure what that even means.

How can a random number be generated differently every time, even after application has relaunched?

Could some data be stored in NSUserDefaults and then, depending on that, different values get generated?

3条回答
再贱就再见
2楼-- · 2019-07-04 02:53

I've been using arc4random, which you don't need to seed. You can give it a try.

查看更多
男人必须洒脱
3楼-- · 2019-07-04 02:55

Here's a discussion on the Apple developer forums.

Use arc4random() instead of either random() or rand(). It used /dev/urandom and generates much better pseudo-random numbers. Both rand() and random() are basically bad random number generators.

See: man arc4random

#include <stdlib.h>
picknumber = arc4random() % 3 + 1; 
查看更多
Ridiculous、
4楼-- · 2019-07-04 03:05

You can seed your random with the following code:

srand([[NSDate date] timeIntervalSince1970]);

This will give you a new random sequence every time.

查看更多
登录 后发表回答