c - Random Array with no repeated numbers -


so trying create random array of 5 elements, elements should filled numbers 1 6 , shall not repeat, can't tell logic wrong.

void gennumber(int vet[]){    int max, i, j, atual;    srand(time(null));     max = 7;    (i=0;i<5;i++){       vet[i] = rand() % max;       while(vet[i] == 0){          vet[i] = rand() % max;       }        for(j=0;j<i;j++){          atual = vet[j];          while((vet[i] == atual)||(vet[i] == 0)){             vet[i] = rand() % max;             atual = vet[j];          }       }    } } 

update: fixed

void gennumber(int vet[]){ int max, i, j; srand(time(null));  max = 7; (i=0;i<5;i++){     vet[i] = rand() % (max-1) + 1;      for(j=0;j<i;j++){         while(vet[j] == vet[i]){             vet[i] = rand() % (max-1) + 1;             j = 0;         }     } } } 

the logical flaw in way produce new random number when duplicate found.

imagine have vel = {1,2,0,0,0,...} , trying find number vel[2]. if randomly draw 2, you'll find it's there , draw again. if draw 1 time won't notice, because compare last value seen, 2 in example. you'd vel = {1,2,1,...}.

"solution": every time draw new random number have compare against all numbers in list.

another way of solving 1 tried outline in comments: have keep information numbers still valid draw somewhere. can either use "output" array you're doing now, or can use store "remove" entry once drawn.


Comments

Popular posts from this blog

html - Difficulties with background-image property -

visual studio code - What does the isShellCommand property actually do and how should you use it? -

ios - Segue not passing data between ViewControllers -