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?
itertoolshas the ability to generate combinations.(x, y)hasx * y = nbits. The number of combination is2^nor2^(x*y). So, for example, an 4x4 array would be2^16 = 65535combinations. A 6x6 is would have 68719476736 combination, larger than what can fit in an int. It quickly gets out of hand.itertools.combinationsbut it doesn't have an option for a 2D array?x*y2d array is the same as an-length 1d array, wherex*y = n. Generate the 1d array, then reshape it to 2d.