Because your algorithm doesn't stop duplicates at all. All you do is assign a random number to each element of the matrix. Many of these number may in fact be the same! (In fact there's a 0.999063343 chance that the array will contain duplicates!)
Firstly, here's the code cleaned up a bit:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int MyArray[3][3];
void checkit(void);
int main(void)
{
srand(time(NULL));
checkit();
int i, j;
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
printf("The Matrix is: %d\n", MyArray[i][j]);
}
}
return 0;
}
void checkit(void)
{
int i, j, RandomNum;
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
RandomNum = rand() % 9 + 1;
MyArray[i][j]=RandomNum;
}
}
}
Try not to define the variable i and j outside a function since they don't need to be. It makes code harder to understand for most people. Writing them inside each function they use has a myriad of benefits which will become apparent as you try more things (thread-safety, modularization, even performance sometimes).
With that said, let's look at an algorithm to give each matrix element a random, but distinct, number. Consider instead if we arbitrarily filled the entire array with the numbers 1 to 9.
Quote
Not very random, eh? But now we can simply loop through all elements of the array and swap it with
any other random element. For example, on the first element we might swap it with sixth element:
Quote
And so on for each element.
Going through each element in this way should ensure quite good pseudo randomness. Here's a modified version of your program to demonstrate:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int MyArray[3][3];
void checkit(void);
int main(void)
{
srand(time(NULL));
checkit();
int i, j;
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
printf("The Matrix is: %d\n", MyArray[i][j]);
}
}
return 0;
}
void checkit(void)
{
int i, j, RandomNum;
//Fill each element with the numbers 1 to 9 in order
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
MyArray[i][j] = 3*i+j+1;
}
}
int d_i, d_j, temp;
//Swap each element with a random other element
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
d_i = rand()%3; //MyArray[d_i][d_j] is the element we will swap with
d_j = rand()%3;
temp = MyArray[i][j];
MyArray[i][j] = MyArray[d_i][d_j];
MyArray[d_i][d_j] = temp;
}
}
}
Consider trying some of the other algorithms we discussed. They are good practice.