编辑: 很抱歉由于我的问题不详细而给您带来不便。
所以,我有一个包含 1000 个单元格的数字 (int) 数组(索引 0-999) 我需要通过调用 C 中的 rand() 函数来用唯一的随机数填充数组的所有单元格,但我只需调用该函数 1000 次即可完成此操作。(生成的每个数字都插入到数组中),数组中不能有重复的数字。
我有什么想法可以做到吗?
注意: 下面是一个示例代码,用于填充数组而不限制调用 rand 的次数。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DO_RAND rand()%1000
#define ARR_SIZE 1000
int main()
{
int i,callToRand=0,j;
int array[ARR_SIZE];
srand(time(NULL));
for(i=0;i<ARR_SIZE;i++) //Runs on the whole array
{
array[i]=DO_RAND; //inserting random number to the array
callToRand++; //increasing the number of calls to rand() function
for(j=0;j<i;j++) //running on the array till the current cell
{
if(array[j]==array[i])
//checking if the number has already in the array.
{
array[i]=DO_RAND;
callToRand++;
j=-1; //staring the checker loop again
}
}
}
printf("The number of calls to the function rand() were: %d\n",callToRand);
system("PAUSE");
return (0);
}
最佳答案
最后声明您想要一个数组大小范围内的唯一数字数组,请尝试此操作。请注意,数字不是随机的 - 它们是定义的 - 顺序是。
您发布的尝试使用两个嵌套循环,效率非常低。这使用一个循环来初始化数组,并使用另一个循环来随机化序列。无需计算对 rand()
的调用,这显然是 ARR_SIZE
。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ARR_SIZE 100 //1000
int main()
{
int i, j, temp;
int array[ARR_SIZE];
srand((unsigned)time(NULL));
for(i=0; i<ARR_SIZE; i++) // set up unique array
array[i] = i;
for(i=0; i<ARR_SIZE; i++) { // randomize the sequence
j = rand() % ARR_SIZE; // pick another (or same) index
temp = array[i]; // and swap the values
array[i] = array[j];
array[j] = temp;
}
for(i=0; i<ARR_SIZE; i++) // show results
printf ("%5d", array[i]);
printf ("\n");
return (0);
}
关于c - 最少调用 rand() C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28014332/