Writing unique numbers to an array
Hi,
Am writing this program to write only unique random numbers to an array. The randomly generated numbers isnt the problem, its writing only unique numbers to the array thats a bother. Any ideas?
Code:
/*A program to generate random numbers and then write them to an array ONLY IF no such number exists in the array*/
#include <stdio.h>
#include <stdlib.h>
int GetRand(int min, int max);
int const MAX=5;
int main(void)
{
int i, r, j,x;
int array[MAX];
for (i = 0; i < MAX; i++)
{
r = GetRand(0, 4); //generate random numbers btwn the 2 numbers indicated
printf ("the random number is %d\n", r);
if(i == 0 ) //writing first generated # to the array automatically for obvious reasons
{
array[0]=r;
printf("array[0]: %d\n\n",array[0]);/*this line works*/
}//end of if statement
if( i > 0 )//comparing from the 2nd # & upwards generated to whats in the array already
{
for( j=1; j<MAX+1; j++ )
{
if(r == array[j-1])
{
i=i-1;
break;
}
else x=1;
}
if( x = 1 )
array[j]=r;
}//end of if statement
}//end of for loop
return(0);
}
int GetRand(int min, int max) //function to generate random numbers
{
static int Init = 0;
int rc;
if (Init == 0)
{
srand(time(NULL));
Init = 1;
}
rc = (rand() % (max - min + 1) + min);
return (rc);
}//end of GetRand function