Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

c - Generating Unique Random Numbers in an Array using Loop

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 
", board[outerLoop][innerLoop] );
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you want is a shuffle algorithm

Shuffle array in C

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("
");
    }   

$ 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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...