I have created a function that is supposed to shuffle the values in an array, I am having issues though - it doesn't seem to shuffle very well and I'm looking for some insight about how to go about it better.
Code:
void shuffle(int* a, int size){
srand((unsigned)time(0));
for (int i = 0; i < (size-1); ++i) {
int r = i + (rand() % (size-i)); // Random remaining position.
int temp = a[i]; a[i] = a[r]; a[r] = temp;
}
}
By not shuffling very well, I mean that I will frequently get the same result twice in a row.
EDIT
I also came up with this:
Code:
void shuffle(int* a, int size){
srand((unsigned)time(0));
for (int i = 0; i < (size-1); ++i) {
double x=rand()/(RAND_MAX+1.0);
int r = (int)(x * (size - 1));
int temp = a[i]; a[i] = a[r]; a[r] = temp;
}
}
it works well. Still, I'd like to see suggestions if anyone has any.
Thanks!