To make things more efficient (and supposing there are sufficiently less solutions than permutations), an idea is:
- Generate all permutations one by one.
- Don't interpret the permutation in its usual way, but interpret it as telling for each digit to which position it will go. So given a permutation
(3, 2, 0, 1)
interpret it as 0 goes to pos 3, 1 goes to pos 2, 2 to pos 0, 3 to pos 1 (so, the inverse permutation: (2, 3, 1, 0)
). Then, the test to accept a permutation or not, is much more straightforward.
Here is an implementation in Python, but the same idea can be applied in any programming language:
from itertools import permutations
num = 0
q = [0 for _ in range(8)] # create a list to fit 8 values
for p in permutations(range(8)):
if p[0] < p[1] < p[3] and p[2] < p[3] and p[4] < p[5] and p[6] < p[7]:
for i, pi in enumerate(p):
q[pi] = i
num += 1
print(num, q)
Output:
1 [0, 1, 2, 3, 4, 5, 6, 7]
2 [0, 1, 2, 3, 4, 6, 5, 7]
3 [0, 1, 2, 3, 4, 6, 7, 5]
4 [0, 1, 2, 3, 6, 4, 5, 7]
5 [0, 1, 2, 3, 6, 4, 7, 5]
6 [0, 1, 2, 3, 6, 7, 4, 5]
...
1257 [4, 6, 7, 5, 2, 0, 1, 3]
1258 [6, 4, 5, 7, 2, 0, 1, 3]
1259 [6, 4, 7, 5, 2, 0, 1, 3]
1260 [6, 7, 4, 5, 2, 0, 1, 3]