1

I am trying to generate all possible 2D arrays (of size n*n) of 0 and 1. Since there are two choices for each entry of the 2D array, there are 2^{n^2} such arrays that need to be generated.

I have a code that generates all possible 1D arrays (of size n) of 0 and 1. It is:

def generateAllSpinConfigs(n,arr,l,i):
    if i == n: 
        l.append(arr[:]) 
        return

    arr[i] = 0
    generateAllSpinConfigs(n,arr,l,i+1)  
    arr[i] = 1
    generateAllSpinConfigs(n,arr,l,i+1)  

    return l

arr=[None]*n 
l=[]
answer=generateAllSpinConfigs(n,arr,l,0)

I understand how that works. In this recursive code, the lowest function call returns an array of all 0 first, then an array with all 0 with a 1 in the last location and so on. Can we extend this logic to generate all 2D arrays or is there a Python function that does the job that I'm not aware of?

10
  • itertools has the ability to generate combinations. Commented Jul 22, 2022 at 19:33
  • Consider that a binary array can be seen a number. A 2D array of dimension (x, y) has x * y = n bits. The number of combination is 2^n or 2^(x*y). So, for example, an 4x4 array would be 2^16 = 65535 combinations. A 6x6 is would have 68719476736 combination, larger than what can fit in an int. It quickly gets out of hand. Commented Jul 22, 2022 at 19:40
  • Due to the above, a recursive algorithm won't get far. Commented Jul 22, 2022 at 19:41
  • @Ouroborus True, it increases exponentially. Thanks, I am aware of itertools.combinations but it doesn't have an option for a 2D array? Commented Jul 22, 2022 at 19:41
  • 1
    A x*y 2d array is the same as a n-length 1d array, where x*y = n. Generate the 1d array, then reshape it to 2d. Commented Jul 22, 2022 at 19:45

1 Answer 1

1

You can use itertools.product. First to generate 1-dimensional lists, and then again to use that as a basis to increase the dimension:

from itertools import product

def get_bin_rows(size):
    return product(range(2), repeat=size)

def get_bin_matrices(size):
    return product(get_bin_rows(size), repeat=size)

Example use for n=2:

for matrix in get_bin_matrices(2):
    # print matrix row by row
    for row in matrix:
        print(*row)
    print()  # separate matrix outputs
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.