lundi 6 avril 2020

Generating/Placing k random items in a 2d array

I have a 2d array, matrix of a sort (m x n). I need to generate '1' in k cells, but the probability of it should be equal for each cell.

for example, if k=3, we pick randomly where to place the 3 '1's :

[0, 0, 0, 0]

[0, 1, 1, 0]

[1, 0, 0, 0]

At first, I tackled this by generating a Random of modulu m * n (rows * columns). But, that means that we could theoretically get to the end of the matrix without generating a single '1'.

Then, I read about Yates Shuffle, but wasn't sure whether that's wise and even feasible to implement it with that.

What is an efficient way to implement this?




Aucun commentaire:

Enregistrer un commentaire