Given a set of N elements, I want to choose m random, non-repeating subsets of k elements.
If I were looking to generate everything , then N would choose k combinations, I could use itertools.combination , so one way to do what I ask is:
import numpy as np
import itertools
n=10
A = np.arange(n)
k=4
m=5
result = np.random.permutation([x for x in itertools.permutations(A,k)])[:m]
print(result)
The problem, of course, is that this code first generates all possible permutations, and this can be quite expensive.
Another suboptimal solution would be to choose randomly each time one swap ( for example, select from random-from-combinations , then sort to get the swap), and discard it if it is already selected.
Is there a better way to do this?
source
share