mercredi 23 mars 2016

Random pairs from two lists

My question is similar to this one.

I have two lists: X with n elements and Y with m elements - let's say they hold row and column indices for a n x m matrix A. Now, I'd like to write something to k random places in matrix A.

I thought of two solutions:

  1. Get a random element x from X and a random element y from Y. Check if something is already written to A[x][y] and if not - write. But if k is close to m*n I can shoot like this for ever.
  2. Create an m*n array with all possible combinations of indices, shuffle it, draw first k elements and write there. But the problem I see here is that if both n and m are very big, the newly created n*m array may be huge (and shuffling may take some time too).

Are there any other (better) approaches I missed?




Aucun commentaire:

Enregistrer un commentaire