我正在尝试用 C 语言生成 80 个字符的固定字符串的随机排列。令我沮丧的是,我正在使用的系统缺少 strfry()。生成此字符串的随机排列的最佳方法是什么?因为这将循环播放大约。 10万次,性能是个问题。
最佳答案
只需使用由 Google Code 发现的开源 GLIBC 实现.
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 特定的数据类型更改为更通用的类型。
此代码使用 Fisher-Yates shuffle其实自己实现起来还是很容易的,而且效率很高。
关于c - 在C中随机化一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/402674/