-1

I have the numbers 0 to 7. A possible combination has to contain all the numbers. A solution has 8 digits. In addition to that these rules apply:

0 comes before 1
1 comes before 3
2 comes before 3
4 comes before 5
6 comes before 7

Example Solutions: 01234567,20134567

Invalid Solutions: 01123456 or 31204567

First of all: Since this is not an exercise from university but an real problem I encountered writing a real program I'm not even sure if an easy solution to this exists. But if there is I would appreciate an answer.

MenNotAtWork
  • 145
  • 2
  • 8
  • 2
    No time-restrictions? Just brute-force it (generate all like a bounded counter; check each). Too lazy for customized alg (and be more generic for upcoming changes)? Model it as constraint-programming problem and use any given solver. Customized algs will probably be based on topological sorting and co. but i would not go for this without a good reason. – sascha Mar 26 '20 at 19:00
  • 1
    What is the problem? There are only some 41,000 orders of 8 digits. Just list them while skipping those which do not match the rules. That won't tax any current computer unduly. You will have to focus on some specific problem you encountered while trying this yourself. – Yunnosch Mar 26 '20 at 19:07
  • You are probably right. I should just brute force it since the pool is not that extensive. I just thought that brute forcing would be heavy on the processor but it seems that it is not the case here. – MenNotAtWork Mar 27 '20 at 03:40

1 Answers1

1

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]
JohanC
  • 71,591
  • 8
  • 33
  • 66