I need all permutations of a bool array, the following code is inefficient, but does what I want:
JavaScript
x
9
1
from itertools import permutations
2
import numpy as np
3
n1=2
4
n2=3
5
6
a = np.array([True]*n1+[False]*n2)
7
8
perms = set(permutations(a))
9
However it is inefficient and fails for long arrays. Is there a more efficent implementation?
Advertisement
Answer
What about sampling the combinations of indices of the True values:
JavaScript
1
7
1
from itertools import combinations
2
import numpy as np
3
4
a = np.arange(n1+n2)
5
6
out = [np.isin(a, x).tolist() for x in combinations(range(n1+n2), r=n1)]
7
Output:
JavaScript
1
11
11
1
[[True, True, False, False, False],
2
[True, False, True, False, False],
3
[True, False, False, True, False],
4
[True, False, False, False, True],
5
[False, True, True, False, False],
6
[False, True, False, True, False],
7
[False, True, False, False, True],
8
[False, False, True, True, False],
9
[False, False, True, False, True],
10
[False, False, False, True, True]]
11