Vinicius Morais
Vinicius Morais

Reputation: 595

How generate all combinations of a binary array without repeating

I am trying to generate an array of all combinations of an array, but how can I generate without repeating.

My first solution was just remove the repeating elements using some for, but I am dealing with big arrays, with 50 length size or more and the execution never end.

ex: (0,0,1,0)

[1,0,0,0]
[0,1,0,0]
[0,0,1,0]
[0,0,0,1]

Upvotes: 1

Views: 172

Answers (3)

treuss
treuss

Reputation: 2388

If your array is really just 0s and 1s, another possibility is to use itertools.combinations to determine, where the 1s are in every combination. Example:

from itertools import combinations

array = [0,0,1,1,0,1,0,1,0,0,1,0,1,0,1]
n = len(array)
k = sum(array)

for comb in combinations(range(n), k): # Any combination to chose k numbers from range 0..n
    next_arr = [1 if i in comb else 0 for i in range(n)]
    print(next_arr)

Upvotes: 3

treuss
treuss

Reputation: 2388

Use itertools.permutations, store results in a set (as itertools.permutations treats elements as unique based on their position, not on their value).:

>>> from itertools import permutations
>>> set(permutations([0,0,1,0]))
{(0, 0, 1, 0), (1, 0, 0, 0), (0, 0, 0, 1), (0, 1, 0, 0)}

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113978

for your example with 4 spaces

you can represent from 0(0000) up to 2**4-1 or 15 (1111)

so you can make all the binary combos with

arrays = [list(f"{i:04b}") for i in range(2**4)]

Upvotes: 0

Related Questions