随机字符串在C中字符串

由网友(时光吹老了好少年*)分享简介:我想产生一个在C. 80个字符的固定字符串的随机置换令我沮丧的是,该系统我的工作缺乏strfry()。什么是对我产生一个随机排列此字符串的最佳方式?因为这将在大约环绕在。 10万次,性能是一个问题。I'm trying to generate random permutations of an 80-characte...

我想产生一个在C. 80个字符的固定字符串的随机置换令我沮丧的是,该系统我的工作缺乏strfry()。什么是对我产生一个随机排列此字符串的最佳方式?因为这将在大约环绕在。 10万次,性能是一个问题。

I'm trying to generate random permutations of an 80-character fixed string in C. Much to my dismay, the system I'm working on lacks strfry(). What's the best way for me to generate a random permutation of this string? Since this will be looped over approx. 100,000 times, performance is an issue.

推荐答案

只需使用开源GLIBC实施,由Google code 。

Just use the Open Source GLIBC implementation, as found by Google Code.

char *
strfry (char *string)
{
  static int init;
  static struct random_data rdata;
  size_t len, i;

  if (!init)
    {
      static int state[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };
      rdata.state = NULL;
      __initstate_r (time ((time_t *) NULL), state, 8, &rdata);
      init = 1;
    }

  len = strlen (string);
  for (i = 0; i < len; ++i)
    {
      int32_t j;
      char c;

      __random_r (&rdata, &j);
      j %= len;

      c = string[i];
      string[i] = string[j];
      string[j] = c;
    }

  return string;
}

您可能要更改glibc的特定数据类型的东西更通用。

You might want to change the GLIBC specific data types to something more generic.

这code使用费雪耶茨洗牌这实际上是很容易自行实施,效率极高。

This code uses the Fisher-Yates shuffle which is actually quite easy to implement by yourself, and very efficient.

阅读全文

相关推荐

最新文章