Peatherfed
Peatherfed

Reputation: 210

How can I generate all different 2D-arrays of a fixed size from a fixed set?

Essentially what I want is: given an m x n array, and a non-empty set, to generate all different lists containing those elements. For example, given a 2x2 array, and the set {0,1,2}, I'd expect back:

[[0, 0], [0,0]]

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

[[0, 0], [0,2]]

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

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

[[0, 0], [1,2]]

[[0, 0], [2,0]]

[[0, 0], [2,1]]

[[0, 0], [2,2]]

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

and so on. I'm working in Python, but pseudo-code or anything like that would be fine. I just can't seem to figure out how to do this.

Upvotes: 1

Views: 43

Answers (1)

Osman Mamun
Osman Mamun

Reputation: 2882

from itertools import product
x = [0, 1, 2] #define the set you want to work on
b = product(x, repeat=4)
# repeat should be the sum of dimension of the desired output 2+2 = 4 in this case
c = [[i[:2], i[2:]] for i in b]
#outputs [[(0, 0), (0, 0)], [(0, 0), (0, 1)], [(0, 0), (0, 2)], [(0, 0), (1, 0)], ...

Upvotes: 1

Related Questions