1

ObjC 上最好的种子随机数生成器是什么?

我必须在 2 部不同的 iPhone 上生成相同的随机数序列,因此必须对其进行播种。这就是为什么我不能使用arc4rand().

注意:最好的意思是最快/最不可预测的关系。

4

1 回答 1

1

C++ 标准库自带的Mersenne Twister 实现非常好。由于它是 C++,因此您需要创建一个包装器,以便您可以从 C 和 ObjC 代码中调用它,或者将使用它的文件重命名为具有 .mm (Objective-C++) 扩展名。

我正在考虑这样的事情,在标题中:

#ifdef __cplusplus
extern "C" {
#endif

struct rng_state;
struct rng_state* create_rng(unsigned seed);
void destroy_rng(struct rng_state* rng);
unsigned long long rng_random_unsigned(struct rng_state* rng, unsigned long long max);

#ifdef __cplusplus
}
#endif

然后,在包含上述内容的 .cpp 文件中:

#include <random>
struct rng_state
{
  std::mt19937* rng;
};
struct rng_state* create_rng(unsigned seed)
{
  std::mt19937* engine = new std::mt19937(seed);
  rng_state* state = new rng_state;
  state->rng = engine;
}
void destroy_rng(struct rng_state* rng)
{
  delete rng->rng;
  delete rng;
}
unsigned long long rng_random_unsigned(struct rng_state* rng, unsigned long long max)
{
  std::uniform_int_distribution<unsigned long long> distribution(0, max);
  return distribution(*rng->rng);
}

I haven't tested the above, but it should be pretty close. You can then include the header in your C/ObjC files as usual, create a rng with a seed, get a bunch of random numbers, and destroy the rng when you're done. You can also add more generator functions if needed - the library comes with different random distributions you can use.

于 2012-11-26T14:18:54.433 回答