Max*_*Max 6 c random algorithm
我试图在C中生成一个80个字符的固定字符串的随机排列.令我沮丧的是,我正在研究的系统缺乏strfry().对我来说,生成此字符串的随机排列的最佳方法是什么?因为这将循环约.100,000次,性能是一个问题.
Kon*_*lph 13
只需使用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;
}
Run Code Online (Sandbox Code Playgroud)
您可能希望将GLIBC特定数据类型更改为更通用的数据类型.
这段代码使用了Fisher-Yates shuffle,它实际上非常容易实现,非常有效.