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

大城市里の小女人 提交于 2020-01-03 05:29:07

问题


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.


回答1:


If you are searching for a random number in range 1...n but excluding some number m in that range, you can instead get a random number in range 1...(n-1) and for any result >= m add 1 to the value.

If you are looking for an explanation of an algorithm for shuffling a finite list, take a look at Fisher-Yates here: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle




回答2:


Here is the solution, it involves a little bit of both.

void Shuffle(int[] arr, size_t n)
{
  int newIndx = 0;
  int i = 0;

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

    swap(i, newIndx, arr);
  }
}

No need to loop until there is a good (random number != i), cuz it is fixed with the if + increment of newIndx.



来源:https://stackoverflow.com/questions/48099203/shuffle-an-array-of-int-in-c-with-without-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!