John Christopher
John Christopher

Reputation: 9

C Programming; Producing a 2-Dimensional Matrix with Random Numbers without Repetition

I'd like to produce a 6x6 matrix by inserting random numbers to the elements in the row and column without repeating. This is my code so far. Thank you for your help!

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

int main(void)
{
int array[6][6];
int rows, columns;
int random;

srand((unsigned)time(NULL));

for(rows=0;rows<6;rows++)
    {
        for(columns=0;columns<6;columns++)
            {
                random=rand()%36+1;

                array[rows][columns] = random;
                printf("%i",array[rows][columns]);
            }

        printf("\n");
    }

return 0;
}

Upvotes: 0

Views: 10675

Answers (2)

Abhishek Panjabi
Abhishek Panjabi

Reputation: 439

try this:

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

int main()
{
    int array[6][6];
    int rows,columns;
    int random,i;
    int randvalues[36],m=0;
    int t,j;


    for(i=0;i<36;i++)     //assigning values 1 to 36 
         randvalues[i]=i+1;

    for(i=0;i<36;i++)      //shuffle logic
    {
         j=i+rand()/(RAND_MAX/(36-i) + 1);
         t=randvalues[j];
         randvalues[j] = randvalues[i];
         randvalues[i] = t;
    }

    for(rows=0;rows<6;rows++) //conversion from 1-D to 2-D array and printning
    {
        for(columns=0;columns<6;columns++)
        {
            array[rows][columns] = randvalues[m++];
            printf("%d " , array[rows][columns]);
        }
        printf("\n");
    }
    return 0;
}

Upvotes: 1

user3386109
user3386109

Reputation: 34829

To avoid repetition:

  1. create a 1D array of 36 elements
  2. fill the 1D array with the numbers 1 thru 36
  3. Fisher-Yates shuffle the 1D array
  4. use the shuffled contents of the 1D array to initialize the 2D array

Upvotes: 3

Related Questions