我有点麻烦让我的文字以随机顺序打印出来。我插入的8个单词需要以随机顺序打印出来。现在我只能以随机顺序生成其中一些,因为如果生成两次相同的数字,它会覆盖前一个空格。我该如何消除这个问题?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <ctype.h>
#define MAX 50
int readLine(char string[]);
int main(void)
{
int i;
char str[8][MAX], temp[8][MAX];
srand((unsigned)time(NULL));
int r_num;
printf("Enter 8 words:\n");
for(i=0; i<8; ++i)
{
readLine(str[i]);
}
for (int i = 0; i < 8; i++)
{
r_num = rand()%8+1;
strcpy(temp[r_num], str[i]);
}
printf("\nRandom order of words: \n");
for(i=0; i<8; ++i)
{
printf("%s\n", temp[i]);
}
printf("\n");
return 0;
}
int readLine(char string[])
{
int ch;
int i=0;
while (isspace(ch = getchar()))
;
while (ch != '\n' && ch != EOF)
{
if (i < MAX)
{
string[i++] = ch;
ch = getchar();
}
}
string[i] = '\0';
return i;
}
答案 0 :(得分:1)
重新排列数据的方法之一是从尚未选择的内容中挑选。
int main(void)
{
int i;
char str[8][MAX];
int order[8]; /* order list */
srand((unsigned)time(NULL));
int r_num;
printf("Enter 8 words:\n");
for(i=0; i<8; ++i)
{
readLine(str[i]);
}
/* initialize order list */
for (i = 0; i < 8; i++)
{
order[i] = i;
}
for (i = 7; i > 0; i--) /* select from back to front */
{
int pos = rand() % (i + 1); /* pick one position randomly */
/* pick selected element by swapping */
int temp = order[pos];
order[pos] = order[i];
order[i] = temp;
}
printf("\nRandom order of words: \n");
for(i=0; i<8; ++i)
{
printf("%s\n", str[order[i]]); /* print strings in the shuffled order */
}
printf("\n");
return 0;
}
答案 1 :(得分:1)
您需要注意不要将相同的数据复制到临时数组中。
您可以查看以下简单逻辑,
1)找到randno r_num
2)交换。 str [r_num]和str [maxlen]
3)将最大len减1
4)重复
for ( i = 0; i < 8; i++)
{
// Commenting your code
//r_num = rand()%8+1;
//strcpy(temp[r_num], str[i]);
memset(temp1,0,sizeof(temp1));
r_num = (rand()%(8-i))+1;
if(r_num != i) // Do not swap if r_num is max
{
//swapping
strcpy(temp1,str[r_num]);
strcpy(str[r_num],str[7-i]);
strcpy(str[7-i],temp1);
}
}
我希望这会对你有所帮助:)。
答案 2 :(得分:0)
在将输入行string[i]
存储在随机输出行temp[r_num]
之前,您只需验证所选输出是否空闲。
第一步,从第一步初始化输出数组
temp[8][MAX]
循环:
for(i=0; i<8; ++i)
{
strcpy(temp[i],""); // set each output line to free (empty).
readLine(str[i]);
}
第二步,在所选字符串上循环随机化选择器 不输出: 随机索引应为0到7。
for (i = 0; i < 8; i++)
{
do {
r_num = rand()%8; // index is between 0 and 7
} while (strlen(temp[r_num])!=0); // output shall be free/empty
strcpy(temp[r_num], str[i]);
}
而不是:
for (int i = 0; i < 8; i++)
{
r_num = rand()%8+1; // error index start from 0
strcpy(temp[r_num], str[i]);
}