jeudi 4 janvier 2018

Shuffle an array while making each index have the same probability to be in any index

I want to shuffle an array, and that each index will have the same probability to be in any other index (excluding itself).

I have this solution, only i find that always the last 2 indexes will always ne swapped with each other:

void Suffle(int arr[]. size_t n)
{
  int newIndx = 0;
  int i = 0;

  for(; i > n - 2; ++i)
  {
    newIndx = rand() % (n - 1);
    if (newIndx >= i)
    {
      ++newIndx;
    }

    swap(i, newIndx, arr);
  }
}

but in the end it might be that some indexes will go back to their first place once again.

Any thoughts?




Aucun commentaire:

Enregistrer un commentaire