How do I compute all possibilities for an array of numbers/bits (in python, or any language for that matter)
In Python, use itertools for stuff like this
from itertools import product
for i in product([0,1], repeat=5):
print i
Yields:
(0, 0, 0, 0, 0)
(0, 0, 0, 0, 1)
(0, 0, 0, 1, 0)
(0, 0, 0, 1, 1)
(0, 0, 1, 0, 0)
etc...
I would approach this problem by just looping from 0 to 31 (0b11111) and turning the binary representation into an array of fixed length.
You didn't tag this with a language, so I'm not sure how to give you example code, but that approach should work.
1: 00001
2: 00010
3: 00011
...
30:11110
31:11111
Edit: Just saw you tagged this question with Python. Sample python code implementing the above algorithm:
listLength=5
for x in range(0,2**listlength):
print(list(bin(x)[2:].zfill(listlength)))
prints out:
['0', '0', '0', '0', '0']
['0', '0', '0', '0', '1']
['0', '0', '0', '1', '0']
['0', '0', '0', '1', '1']
['0', '0', '1', '0', '0']
['0', '0', '1', '0', '1']
['0', '0', '1', '1', '0']
['0', '0', '1', '1', '1']
['0', '1', '0', '0', '0']
['0', '1', '0', '0', '1']
['0', '1', '0', '1', '0']
['0', '1', '0', '1', '1']
['0', '1', '1', '0', '0']
['0', '1', '1', '0', '1']
['0', '1', '1', '1', '0']
['0', '1', '1', '1', '1']
['1', '0', '0', '0', '0']
['1', '0', '0', '0', '1']
['1', '0', '0', '1', '0']
['1', '0', '0', '1', '1']
['1', '0', '1', '0', '0']
['1', '0', '1', '0', '1']
['1', '0', '1', '1', '0']
['1', '0', '1', '1', '1']
['1', '1', '0', '0', '0']
['1', '1', '0', '0', '1']
['1', '1', '0', '1', '0']
['1', '1', '0', '1', '1']
['1', '1', '1', '0', '0']
['1', '1', '1', '0', '1']
['1', '1', '1', '1', '0']
import numpy as np
def all_combinations(width, vals):
return np.array(np.meshgrid(*[vals]*width,
indexing='ij')).reshape((width,-1)).transpose()
print(all_combinations(width=3, vals=[0,1]))
print(all_combinations(width=2, vals=['a','b','c']))
Output:
[[0 0 0]
[0 0 1]
[0 1 0]
[0 1 1]
[1 0 0]
[1 0 1]
[1 1 0]
[1 1 1]]
[['a' 'a']
['a' 'b']
['a' 'c']
['b' 'a']
['b' 'b']
['b' 'c']
['c' 'a']
['c' 'b']
['c' 'c']]