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).
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With