c - 使用循环在数组中生成唯一随机数

标签 c arrays loops random

所以问题是开发一个 [5][5] 表,每个表包含从 1 到 100 的唯一数字(没有重复)

所以这是我想出的:

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

int main()
{
    int outerLoop;
    int innerLoop;

    int board[5][5]; /* Array Name And Size*/

/* seeds the random number generator*/

srand(time(NULL));

int number;

number = rand() % 101;

/* Start a loop to generate a random integer between 1 and 100 and 
assign it into the array. The loop runs 25 times*/

for (  outerLoop = 0  ;  outerLoop <= 25  ; outerLoop++ ) /* loop 25 times*/
{
    for (  innerLoop = 0  ;  innerLoop <= 4  ; innerLoop++   ) /* <=4 due to 5
columns*/
    {
        board[outerLoop][innerLoop] = rand() % 100 + 1;
    }
    printf( "%d \n", board[outerLoop][innerLoop] );
}

所以我几乎被困在这里。我对此不太确定:

board[outerLoop][innerLoop] = rand() % 100 + 1;

我只是编造出来的:/伙计们有什么想法吗?

最佳答案

你要的是一个shuffle算法

Shuffle array in C

要获得从 1 到 100 的唯一 #s 的 25 个元素数组;只需创建一个包含数字 1..100 的 100 元素数组,从 100 的池中洗牌第 25 个,然后使用第 25 个。

$ cat test.c
    #include <stdio.h>
    #include <stdlib.h>

    void shuffle(int *array, size_t array_size, size_t shuff_size)
    {   
        if (array_size > 1)  
        {   
            size_t i;
            for (i = 0; i < shuff_size - 1; i++) 
            {   
              size_t j = i + rand() / (RAND_MAX / (array_size - i) + 1); 
              int t = array[j];
              array[j] = array[i];
              array[i] = t;
            }   
        }   
    }   

  int main(int argc, char * argv[]) {
        int a[100];
        int b[5][5];
        int i,j,k=0;

        for(i=0; i<100;++i)
            a[i]=i;

        shuffle(a,100,25);

        for(i=0;i<5;++i)
            for(j=0;j<5;++j) {
                b[i][j] = a[k++];
                printf("%d ",b[i][j]);
        }
        printf("\n");
    }   

$ gcc -o test test.c

$ ./test
0 14 76 47 55 25 10 70 7 94 44 57 85 16 18 60 72 17 49 24 53 75 67 9 19 

关于c - 使用循环在数组中生成唯一随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28314022/

相关文章:

c - 由于 fopen() 和 FILE 导致无法解释的错误

javascript - 将数组中的多个元素移动到数组中的某个索引

loops - 我应该避免重置 "by hand"一个自动递增的循环变量吗?

具有意外 cpu 消耗的 C 多线程进程

javascript - 当控制台显示 "Cannot read property ' length' of undefined 时,这是什么意思?

python - Python 中的字母顺序

c - 获取的不仅仅是数据集中的属性名称和值

c - C中的动态二维数组不读取第一个元素

c - wchar_t 和多字节函数是 ANSI C 的一部分吗?

python - 如何比较 Python 中的二维列表是否相等?