开发者

Runtime Random Generators, not Compile Time [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

iPhone: random() function gives me the same random number everytime

I am writing a test iPhone app for a larger project that I am working on that will involve randomize开发者_JAVA技巧d strings, numbers, etc. When I use the rand() or random() functions, every single time I do get randomized numbers and strings, but in the same order! I know that the compiler determines the order at compile time, but do not want that. I want it to be completely random, so something different every time not just a predetermined list. What I have tried is a loop that counts up and down to try to take a value from that but it didn't work.


The compiler doesn't generate the random strings; they're generated at runtime. But they are generated based on an initial seed; for a given value of the seed, you'll get the same sequence of numbers. You need to choose a seed at runtime based on something like the system time, uptime, count of user clicks, etc.


You need to seed the number for rand. This way it will be random every time!

Here is an example of what I mean:

// Seed number for rand() 
srand((unsigned int) time(0) + getpid());

Add the above line of code before using rand()


Random number generators are never truly "random," and instead generate a number based on something that should always be different. Giving a random number generator a unique value so that it can generate a random number is know as "seeding." For rand(), you will want to seed it with srand(time(NULL)). For random() it's the same deal with srandom(). There are functions available for iOS such as arc4random(), which is self-seeding. To generate a random number up to (but not including) 10, for instance, you could use arc4random() as follows:

int random = arc4random() % 10;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜