Generating/Placing k random items in a 2d array

陌路散爱 提交于 2020-06-27 06:17:01

问题


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?


回答1:


This is essentially a problem of "sampling without replacement": Out of mn cells, choose k of them without replacement. There are many approaches to this problem, depending on how big mn is in relation to k. If mn is relatively small, then a Fisher–Yates shuffle will work well; make a list of cells, shuffle them, then take the first k cells to set to 1.

For more details, see my sections on sampling without replacement and shuffling. (Part of my comment moved here:) Different sampling algorithms have different tradeoffs in terms of time and space. For example, a Fisher–Yates shuffle has time and space complexity of O(mn), while a partial shuffle can have time complexity O(k).



来源:https://stackoverflow.com/questions/61065565/generating-placing-k-random-items-in-a-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!