Generating Unique Random Numbers in an Array using Loop

后端 未结 6 2028
臣服心动
臣服心动 2020-12-12 01:36

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:

#inc         


        
6条回答
  •  暖寄归人
    2020-12-12 01:55

    C stores arrays in row-major order, i.e, the elements of row 0 comes first , followed by the elements of row 1, and so forth.

    enter image description here
    We can take advantage of this by viewing int board[5][5] as int board[5*5].

    #include 
    #include 
    #include 
    #define N 5
    
    int main()
    {
        int i, outerLoop = 1;
        int board[N*N];
    
        srand(time(NULL));
    
        int number;
        board[0] = rand() % 100 + 1; //initializing the first element
    
        while(1)
        {
                number = rand() % 100 + 1 ;
    
                if(outerLoop == N*N)
                    break;      
                else
                {
                    //Cheking the previous elements for no duplicacy
                    for ( i = 0; i < outerLoop; i++)
                    {
                        if(number == board[i])
                            break;
                    }
    
                    //confirming whether all the elements are checked or not and the assigning number to the array element and then increment the counter outerLoop 
                    if(i == outerLoop)
                    {
                        board[outerLoop] = number;
                        outerLoop++;
                    }
                    else
                        continue;
                }
    
        }
    
        //Printing the elements of array board[N*N]
        for (  outerLoop = 0  ;  outerLoop < N*N  ; outerLoop++ )
        {
            printf( "%d\t", board[outerLoop] );
            if(outerLoop % N == 4)
                printf("\n\n");
        }
    
    }
    

提交回复
热议问题