使用-不使用while循环对C中的int数组进行混洗 [英] Shuffle an array of int in C with - without while loop

查看:44
本文介绍了使用-不使用while循环对C中的int数组进行混洗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想随机播放一个整数数组,该数组经过排序,其大小为n,值是1-n.我只是想避免使用while循环,以确保rand()不会给我相同的索引.代码看起来像是somthin:

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);
  }
}

for循环一直持续到n-1,因此例如在最后一次运行中,它有50/50的机会等于i.我想避免这个想法.

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 ... n中的随机数,但不包括该范围中的某个数字m,则可以获取范围中的随机数1 ...(n-1),对于> = m的任何结果,将值加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.

如果您正在寻找对有限列表进行混排的算法的说明,请在此处查看Fisher-Yates:

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

这篇关于使用-不使用while循环对C中的int数组进行混洗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆