使用循环数组生成唯一的随机编号 [英] Generating Unique Random Numbers in an Array using Loop

查看:135
本文介绍了使用循环数组生成唯一的随机编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以现在的问题是建立一个[5] [5]表中,每个包含独特的人数从1-100(的没有重复的)

So the question is to develop a [5][5] table, each containing unique numbers from 1-100 (no duplicates)

所以这里就是我想出了:

so here's what I came up with:

#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] );
}

所以我pretty多被困here.I'm不能肯定这一点:

So I pretty much got stuck here.I'm not really sure about this:

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

我只是做它:/任何想法的家伙

I simply made it up :/ Any idea guys?

推荐答案

你想要的是一个洗牌的算法

What you want is a shuffle algorithm

洗牌数组用C

要获得独一无二的#秒25的元素的数组从1到100;只创建与数字1..100 100元件阵列,从100池中洗牌一号25,并用第1 25

To get your 25 element array of unique #s from 1 to 100; just create a 100 element array with the numbers 1..100, shuffle the 1st 25 from the pool of 100, and use the 1st 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 

这篇关于使用循环数组生成唯一的随机编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆