生成隨機字串時遇到問題。
下面的示例生成重復的隨機字串塊。塊中隨機字串的數量取決于“WORD_LENGTH”。對于 1M 'COUNT' 和 'WORD_LENGTH' 的 20 個字符,每個塊包含 262144 (2^18) 個隨機字串,然后塊重復。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define WORD_LENGTH 20
//const char charset[62] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const char charset[16] = "0123456789abcdef";
int main(int argc, char** argv) {
srand(time(NULL));
if (argc != 2) {
printf("Usage: program COUNT'\n\n");
return 0;
}
unsigned int count = atoi(argv[1]);
char buf[WORD_LENGTH];
for (int c = 0; c < count; c ) {
for (int i = 0; i < WORD_LENGTH; i) {
buf[i] = charset[ rand() % sizeof charset];
}
buf[WORD_LENGTH - 1] = '\0';
printf("%s\n", buf);
}
return 0;
}
重要的事情。當“..charset[62]...”與 'COUNT' 高達 100M 一起使用時,我無法重現“問題”。問題:有人可以解釋為什么它會這樣作業嗎?
uj5u.com熱心網友回復:
C在函式中使用偽亂數生成器rand()。因此它們是重復序列。
uj5u.com熱心網友回復:
試試這個怎么樣:
char buf[WORD_LENGTH];
for (int c = 0; c < count; c ) {
for (int i = 0; i < WORD_LENGTH; i) {
buf[i] = charset[ rand() / (RAND_MAX 1u) * sizeof charset];
}
buf[WORD_LENGTH - 1] = '\0';
printf("%s\n", buf);
}
在 C 參考文獻中說,像這樣的代碼rand() % sizeof charset是有偏見的。這個答案可能會給出一些想法。
uj5u.com熱心網友回復:
總結來自@WhozCraig 和@LightVillet 的評論。
在“buf[i] = charset[rand() % sizeof charset]”中發現了問題。與 'rand() % X' 精確并與 'X' 連接而不與 charset 陣列連接。當 X = 4,8,16,32,64 時重現問題。但不能轉載與值之間。用 COUNT 進行了簡短的測驗,最高可達 1M。
小心 rand()
并使用
"(int)(rand()/(RAND_MAX 1.0) * (sizeof charset))"
@Mr.Chip 和 @rici 提到的
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/410345.html
標籤:
