Imagine a 3×3 grid:
[A, B, %]
[C, %, D]
[E, F, G]
The percentages % stand for empty spaces/positions.
The rows can be moved like beads on a string, such that the permutations for the configurations for the first row could be any one of:
[A, B, %] or [A, %, B] or [%, A, B]
Similarly for the second row. The third row contains no empty slots and so cannot change.
I am trying to produce all possible grids, given the possible permutations of each row.
The output should produce the following grids:
[A, B, %] [A, B, %] [A, B, %]
[C, D, %] [C, %, D] [%, C, D]
[E, F, G] [E, F, G] [E, F, G]
[A, %, B] [A, %, B] [A, %, B]
[C, D, %] [C, %, D] [%, C, D]
[E, F, G] [E, F, G] [E, F, G]
[%, A, B] [%, A, B] [%, A, B]
[C, D, %] [C, %, D] [%, C, D]
[E, F, G] [E, F, G] [E, F, G]
I have tried a method of looking through each row and shifting the space left and right, then generating new grids off that and recursing. I keep all grids in a set and ensure I only produce positions which haven’t already been examined to prevent infinite recursion.
However, my algorithm seems to be horrendously inefficient (~1s per permutation!!) and doesn’t look very nice either. I was wondering if there was an eloquent way of doing this? In python in particular.
I have some vague ideas but I’m sure there is a way of doing this which is short and simple which I’m overlooking.
EDIT: 3×3 is just an example. Grid could be of any size and it’s really the row combinations which matter. For example:
[A, %, C]
[D, E, %, G]
[H, I]
is also a valid grid.
EDIT 2: The letters must maintain their order. For example [A, %, B] != [B, %, A] and [B, A, %] isn’t valid
First you have to get all desired permutations for each line. Then you calculate the cross product of all lines.
The permutations of a line can be simple calculated by having the letters [A,B,%] and varying the starting index:
The cross product is easiest to achieve using itertools.product
This solution is optimal in memory and CPU requirements, because permutations are never recomputed.
Example output: