Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 21994

How to generate an array of random & unique integers in C?

$
0
0

I am creating a C-prog that requires an array of 17 integers, all being less than 18 and unique. This is what I could do until now:

int ques_arr[17];int x,y;time_t t;srand((unsigned)time(&t));for(int a=0; a<17; a++){x=rand()%18; //Assume that srand() has been declared in the program for(int aa=0; aa<17; aa++) {  if(x==ques_arr[aa])   { do{        y=0;        y=rand()%18;        }while(y==ques_arr[aa]);      x=y;       ques_arr[a]=x;    }else ques_arr[a]=x;  }}

My current algorithm is that everytime rand() generates a number, that number will be checked throughout array whether same number already exists or not, if it does, rand() keeps on generating a number until a unique number is obtained and then it is stored in the array.If such a number doesn't exist in the array, it's directly fed in to it.

As of now, numbers stored in the array are not unique.

Any help would be appreciated.


Viewing all articles
Browse latest Browse all 21994

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>