如何在随机位置填充具有特定数量的1&0和0的数组?

时间:2017-10-23 18:05:40

标签: c++ arrays sorting random arduino

我有一个数组有8个点填充,4个1和4个零填充它,但希望位置是随机的。我有点难过如何做到这一点,而不是多余。有没有一种简单的方法可以做到这一点,或者我必须随机填充1或0的数组然后检查,看看它是否具有正确数量的两者?我目前的代码是

void setup() {
  int one = 0;
  randomSeed(analogRead(A0));
  for (int i=0; i<8; i++){
    array[i] = random(0, 2);
    if (array[i] == 1){
      one++;
    }
    if(one >4){
      array[i] = 0;
      one--;
    }
  }
}

这大部分都有效,但有一些明显的缺点,所以任何有关更好方法的指针都会受到赞赏。

2 个答案:

答案 0 :(得分:5)

更新:此答案与原始

略有不同

对于资源紧张的Arduino,此代码就足够了,无需链接额外的库:

int a[8] = { 0,0,0,0,1,1,1,1 };


void setup() {

  randomSeed(analogRead(A0));

  for (int n=7;n>0;n--) {
    int r = random(n+1);
    int t = a[n];
    a[n] = a[r];
    a[r] = t;
  }

}

This is exactly how the std::shuffle function is implemented,仅限于内置Arduino random()功能的实施效果

答案 1 :(得分:4)

如果你需要在零数组中生成m个随机数,你可以简单地遍历整个数组并将当前元素设置为1,概率为P

           number of 1's that remains to be set
P = ----------------------------------------------------
    number of array elements that remains to be iterated

在你的情况下,你需要在8个元素的数组中设置4个随机1

const unsigned N = 8, M = 4;
int array[N];

for (unsigned i = 0, m = M; i < N; ++i)
  if (rand() % (N - i) < m)
  {
    array[i] = 1;
    --m;
  }
  else
    array[i] = 0;

这会在一次传递中生成随机数组 - 无需后续随机播放。

P.S。为了使用上述概率[{1}}做出决定,我使用了经常被批评的P方法。当然,这是重点。您可以使用您选择的任何其他方法。