dimanche 13 janvier 2019

Why does filling m/2 slots of a n by n array with randomly generated indices only take 2m tries?

I'm trying to complete this challenge and I'm confused about

Solution explained, commentary

1) if M < NxN/2 then randomly pick spots and if empty place mines. At worst, the chance of picking a mine rather than empty cell is 50% so we need 2M tries.

In summary, when filling up a 10 by 10 array with 50 integer 9s, random row and col is generated, then if array[row][col] already has a 9, we generate new row and column and try again.

Would this technically take forever or at least more than 2 * 50 times as we can get really unlucky as opposed to what the solution says?

The code looks something like this:

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

Also see the official solution code lines 37-55: from https://gist.github.com/dgossow/d28083522608771e1c65f49822820ba9




Aucun commentaire:

Enregistrer un commentaire