I have a square grid represented by a list of list of lists - for example:
grid = [[[9,3], [], [4]],
[[10, 1, 2], [], [11,5]],
[[8], [7, 6], []]]
There is no limit on the lengths of the innermost lists (cells). The grid must contain all integers from 1 to n, where n is a given number (in this case, 11), and each number can only appear once.
I need to select a random number between 1 and n with uniform probability and return the location of the number (i.e. for '3' I would need grid[0][0][1]). Because the probability needs to be uniform, I can't just select a random cell, and then select a random number in the cell, because that would bias the selection towards numbers in cells with fewer numbers in them.
My initial approach has been to generate a random number between 1 and n, and then look through the entire grid for the number. However, the grid can become quite big. What is a more optimal approach to this problem?
Aucun commentaire:
Enregistrer un commentaire