c - C中的非重复随机数生成器

标签 c random numbers

我想编写一个程序,每次运行时打印出 10 个随机数,打印出的随机数应该是 1-10,并且它们不能重复。

更新:很抱歉没有说明确切的问题,基本上 while 循环假设只有在它没有被使用时才重新分配随机数,这导致我的程序根本不打印任何东西。如果我注释掉整个 while 循环并将 printf 留在底部,它会打印出 1-10 之间的 10 个随机数,但它只会重复打印。

有人可以告诉我如何修复我的代码或给我一些提示吗?

#include <stdio.h>
#include <time.h>

int main()
{
int array[10];
int x, p;
int count;
int i=0;

srand(time(NULL));

for(count=0;count<10;count++){
array[count]=rand()%10+1;
}

while(i<10){
int r=rand()%10+1;

for (x = 0; x < i; x++)
{
if(array[x]==r){
    break;
}
if(x==i){
    array[i++]=r;
}
}

}
for(p=0;p<10;p++){
printf("%d ", array[p]);
}
return 0;
}

最佳答案

使用移位掩码算法,可以生成不重复的伪随机数。我已经包含了我的一个函数,在下面给出了一个例子。这个过程比任何其他提供的算法快 10 倍,也不使用额外的内存。这种算法通常用于“数字溶解”和“散射”效果等,但是我的实现侧重于单维效果。

享受, B博士

/* Bryan Wilcutt's random scatter algorithm */
/* Generates random-appearing, non-repeating values. */

/* Can be any number within the given range of 32K 
   Mask must be changed for other ranges.  */

#define START_POINT 1

void randScatter()
{
    long mask;  /* XOR Mask */
    unsigned long point;
    int val;
    unsigned int range = 0x7fff; /* 32K */

    mask = 0x6000; /* Range for 32K numbers */

    /* Now cycle through all sequence elements. */

    point = START_POINT;

    do {
        val = point % range;    /* Get random-appearing value */
        printf("%08x\n", val);

        /* Compute the next value */

        if (point & 1) {
            /* Shift if low bit is set. */

            point = (point >> 1) ^ mask;
        } else {
            /* XOR if low bit is not set */

            point = (point >> 1);
        }
    }  while (point != START_POINT); /* loop until we've completed cycle */
}

关于c - C中的非重复随机数生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23285326/

相关文章:

c - 在辅助函数中使用堆栈

android - HTML5 - Android 平板电脑 - 输入类型编号

java - 获取一个数字的前N位数字

python - 在 Python 中仅从字符串中获取第一个数字

c - 使用 difftime 获取从现在到 future 的时差(以秒为单位)

c - 如何在函数中使用结构体

java - 在 Java 中实现随机 Int

java - Alias 方法的开源实现

java - 随机数生成器表现得很奇怪

c - 如果不为空,则锁定空闲队列入队