Non-repeating random number generator in C -
i want write program print out 10 random numbers every time run it, random numbers printing out should 1-10, should never repeat.
update:sorry not stating exact problem, while loop suppose re assign random numbers if hasent been used causing program not print @ all. if comment out entire while loop , leave printf @ bottom prints out 10 random numbers between 1-10, prints out repeats.
could tell me how can fix code or give me tips?
#include <stdio.h> #include <time.h> int main() { int array[10]; int x, p; int count; int i=0; srand(time(null)); for(count=0;count<10;count++){ array[count]=rand()%10+1; } while(i<10){ int r=rand()%10+1; (x = 0; x < i; x++) { if(array[x]==r){ break; } if(x==i){ array[i++]=r; } } } for(p=0;p<10;p++){ printf("%d ", array[p]); } return 0; }
if(x==i)
can never true inside for (x = 0; x < i; x++)
loop, therefore while
loop never terminate. if statement has moved after for-loop:
while(i<10){ int r=rand()%10+1; (x = 0; x < i; x++) { if(array[x]==r){ break; } } if(x==i){ array[i++]=r; } }
also first loop
for(count=0;count<10;count++){ array[count]=rand()%10+1; }
is unnecessary because values overwritten later.
(if look-up "random permutation" or "fisher–yates shuffle" find more efficient algorithms producing non-repeating sequence of random numbers.)
Comments
Post a Comment