Hello

I have a function that should store random numbers in an array and also check if there are any repeated numbers.

My problem is that I cannot figure out how to 'repair'/get rid of repeated numbers & make them ...unrepeated numbers? :P

Any advice on how I can alter this function? :)

void random(int array[], int max) {

	int n;
	int match = 0;     // check if any numbers are repeated

	for (int i = 0; i < 6; i++)
	{
		n = (rand()%max)+1;
		for (int j=0; j<6; j++) {
			if (n == array[j]) {
				match++;
			}
		}
		if (match==0) {     // if no numbers have been repeated
			array[i] = n;
		}
		else { array[i] = n-1; }  // there are repeats

		match = 0; // reset match variable
	}
}
else { array[i] = n-1; }

Assigning n-1 is a problem, because n-1 might have already been present in the array.
Instead , try to generate another random number for position 'i'.
But the for loop increments the value of 'i' in the next iteration .

Though I have never tried this by myself here might be a possible solution.

else { 
i--;
continue; }

Consider that you have already generated the same number for position 3.

with i-- the value of i is 2. The for loop then increments the value and gets back to 3.

So it generates the number and checks again if the number has already been generated. If no, It would just store it in position 3 and continue.


Though I have never tried this by myself here might be a possible solution.

else { 
i--;
continue; }

Consider that you have already generated the same number for position 3.

with i-- the value of i is 2. The for loop then increments the value and gets back to 3.

So it generates the number and checks again if the number has already been generated. If no, It would just store it in position 3 and continue.

Hmm, I understand your algorithm & thanks :) but when I implement it my program seems to crash?

> for (int j=0; j<6; j++)
You're scanning the whole array, not just the valid values (that would be < i )

> if (match==0)
Nothing resets this back to 0 for checking the next time

Sorry, I havent noticed the

match = 0; // reset match variable

reset statement.

So I guess the alteration would be to

else { 
                      i--;
	               }  // there are repeats

Apart from all this it would be better if you could change the second for-loop to check the already assigned values only instead of the whole array.
This would make the algorithm efficient also.

for (int j=0; j<i; j++) {
This article has been dead for over six months. Start a new discussion instead.