I have a function that generates x (parameter) random numbers, removes repeats, and returns the values stored in an array.
I am using rand() to call random numbers, however if I call the function with x parameter set to 5 it turns into an infinite loop as rand() continuously returns me the same 4 or 5 numbers.
I have only called srand() once in the main().
int main(void){
srand(time(NULL));
erase = eraser(4);
}
int* eraser(int array_size)
{
array_size++;
int* remove_ids = malloc(sizeof(int*) * array_size);
int t, v;
int i;
for(i = 0; i < array_size; i++) {
t = 1+(rand() & 80);
v = 1+(rand() & 80);
printf("t=%d , v=%d\n", t, v);
remove_ids[i] = t;
if(i == 0){
remove_ids[i] = array_size;
}
else {
for(int c = 1; c < i; c++) {
if(remove_ids[c] == t) {
i--;
break;
}
}
}
}
return(remove_ids);
}
Output:
t=1 , v=1
t=81 , v=1
t=81 , v=65
t=65 , v=17
t=17 , v=65
t=17 , v=65
t=1 , v=65
If I call eraser(5) I get stuck in an infinite loop.
Interestingly, on another function in the program rand() functions perfectly.
Aucun commentaire:
Enregistrer un commentaire