Sunday, May 10, 2009

Help! Non- repeating random number generator (C programming)?

I'm trying to generate non-repeating random numbers(within 1-16) in 4x4 matrix, but some numbers among 16 keep repeat. I also want to make the number 16 to be left with a blank, so I put:


if(16 == array[x])


{


array[x] == ' ';


}





which does not work either...





Please help me out!!








#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;time.h%26gt;


int main()


{


int array[16] = {0};


int x;


int y;


int m;


int n;


srand(time(0));


for(x = 1; x %26lt; 17; x++)


{


array[x] = rand()%17;


}


for(x = 1; x %26lt; 17; x++)


{


for(y = 0; y %26lt; 17; y++)


{


if( x != y)


{


if(array[x] == array[y])


{


array[x] = rand()%17;


if(16 == array[x])


{


array[x] == ' ';


}


}


}


}


printf("%5d", array[x]);


if(x%4 ==0)


printf("\n");


system("PAUSE");


return 0;


}

Help! Non- repeating random number generator (C programming)?
So, what you want is to fill an array with 16 numbers, with each number being different, and the number 16 is replaced with a space character, right?


I'll just concentrate on the random number generation and array filling part of your program.





To debug your program, you should simplify it first. For now, ditch the nested loops and printing part, and create a test program which just includes the random number generation and array filling part.





You need an algorithm which works like this:





First, allocate the array in global memory by putting the 'int array[16];' line outside of the 'main()' procedure. (The C start up code automatically zeroes out all global memory variables when you run the program.)





Now do this:


1) Create random number and put it in an int variable.


2) Is the int a value of 16?


3) If so, then change the value to the ' ' character. The ASCII value of ' ' is 32 decimal.


4) In a 'while' loop, compare the int to the other ints in the array. The loop ends if you read a zero in the array.


5) If the int matches a value in the array, go back to step 1.


6) Else, put the int in the array. You need a variable to keep track of which array element to write to.


7) If you haven't written out 16 ints to the array, go back to step 1.





As you can see, the algorithm above requires 2 'while' loops -one inside the other. The inner loop compares the random number to the numbers already in the array. The outer loop runs until the array is filled with 16 ints.





Printing the array is another matter.


No comments:

Post a Comment