jeudi 4 janvier 2018

Shuffle an array of int in C with - without while loop

I want to Shuffle an array of ints, the array is sorted and its size in n, values are 1 - n. I Just want to avoid using a while loop in order to make sure the rand() doesn't give me the same index. the code looks somthin like this:

void shuffleArr(int* arr, size_t n)
{
  int newIndx = 0;
  int i = 0;

  for(; i < n - 1; ++i)
  {
    while((newIndx = i + rand() % (n - i)) == i);

    swap(i, newIndx, arr);
  }
}

The for loop goes until n-1, so for example in the last run it has 50/50 chance of being equal to i. I want to avoid this idea.




Aucun commentaire:

Enregistrer un commentaire