【问题标题】:Randomizing the characters from a word随机化单词中的字符
【发布时间】:2014-07-24 12:02:07
【问题描述】:

我正在尝试弄清楚如何对字符串中的字符进行随机排序,例如“this”、“htis”、“tish”或“hsit”。我相信我的问题在于 rand() 可能在循环中两次选择相同的随机数。比如第二个字符在循环中应用了两次。我也很确定,在循环的最后一次迭代期间,这个循环在某些时候也没有任何可供选择的东西。

我的代码如下:

 int main(void){
setvbuf(stdout,NULL,_IONBF,0);
int size=0;
char word[size];
int i;

printf("Please enter a word: ");
scanf(" %s",&word);
printf("Scanning the size of the word...");
size = strlen(word);
    for(i=0;i<size;i++){
    srand(time(0));
    int j = i + rand() / (RAND_MAX / (size - i) + 1);
    char t = word[j];
    word[j] = word[i];
    word[i] = t;
    }
printf("%i",size);
    for(i=1;i<size+1;i++){
        printf(" %c",word[i]);
    }
return 0;
}

有什么想法吗?

【问题讨论】:

标签: c sorting random


【解决方案1】:

您的实现的问题是您在循环中调用srand。由于循环进行得非常快,因此您以相同的种子值结束 uo 调用 srand,因为 time(0) 没有机会在循环迭代之间进行标记。

将调用移至循环外的srand 以解决此问题。

注意:请参阅 this answer 了解 Fisher-Yates shuffle 的良好 C 实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    • 2015-09-07
    相关资源
    最近更新 更多