Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compute all possibilities for an array of numbers/bits (in python, or any language for that matter)

I have been wracking my brains out for 3 hours straight, but I still don't get it, so I am asking here. (I wrote Python in the title, but this could be for pretty much any language)

Let's assume I have an array of bits (but it may also be integers in a defined range) of fixed length n, let's say 5.

array=[0,1,1,0,0]

Now, how do I generate ALL arrays, which are possible in the number range (in the case of bits, 2).

So:

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

I have tried searching for a solution here, but I always find something which is similar, but which doesn't quite solve my problem.

To solve this, I have tried various loops, but I always end up either getting one possibility more than once (should not happen), or not getting all possible ones.

I can manage to do this with if statements (to check if a combination already exists), but that seems very unsophisticated.

Is there a simple method, using only loops, to obtain all possibilities?

Thank you

Edit: Since this was mentioned below, no, this is not homework. This is for research in order to implement a Bayesian network of binary states. (on/off).

like image 588
John Smith Avatar asked Oct 20 '12 07:10

John Smith


Video Answer


1 Answers

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']]
like image 167
omasoud Avatar answered Oct 21 '22 13:10

omasoud