为什么用随机生成的索引填充n x n数组的m / 2个时隙仅需要2m次尝试?

时间:2019-01-14 04:51:37

标签: arrays random probability

我正在尝试完成this challenge,但对

感到困惑
  

解决方案说明,评论

     

1)如果M

总而言之,当用50个整数9s填充10 x 10数组时,将生成随机行和col,然后,如果array [row] [col]已经具有9,我们将生成新的行和列,然后重试。

从技术上讲,这会永久或至少超过2 * 50倍,因为我们真的会很不幸,而不是解决方案所说的吗?

代码看起来像这样:

int[][] array = new int[10][10];
int placed = 0;
int num_to_place = 50;
while (placed < num_to_place) {
  int row = random.nextInt(10);
  int col = random.nextInt(10);
  if (array[row][col] == 9) {
    continue;
  }

  array[row][col] = 9;
  ++placed;
}

另请参阅官方解决方案代码行37-55: 来自https://gist.github.com/dgossow/d28083522608771e1c65f49822820ba9

0 个答案:

没有答案