Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating all unique combinations for "drive ya nuts" puzzle

A while back I wrote a simple python program to brute-force the single solution for the drive ya nuts puzzle.

alt text
(source: tabbykat.com)

The puzzle consists of 7 hexagons with the numbers 1-6 on them, and all pieces must be aligned so that each number is adjacent to the same number on the next piece.

The puzzle has ~1.4G non-unique possibilities: you have 7! options to sort the pieces by order (for example, center=0, top=1, continuing in clockwise order...). After you sorted the pieces, you can rotate each piece in 6 ways (each piece is a hexagon), so you get 6**7 possible rotations for a given permutation of the 7 pieces. Totalling: 7!*(6**7)=~1.4G possibilities. The following python code generates these possible solutions:

def rotations(p):
    for i in range(len(p)):
        yield p[i:] + p[:i]

def permutations(l):
    if len(l)<=1:
        yield l
    else:
        for perm in permutations(l[1:]):
            for i in range(len(perm)+1):
                yield perm[:i] + l[0:1] + perm[i:]

def constructs(l):
    for p in permutations(l):
        for c in product(*(rotations(x) for x in p)):
            yield c

However, note that the puzzle has only ~0.2G unique possible solutions, as you must divide the total number of possibilities by 6 since each possible solution is equivalent to 5 other solutions (simply rotate the entire puzzle by 1/6 a turn).

Is there a better way to generate only the unique possibilities for this puzzle?

like image 461
Yuval Adam Avatar asked Jan 23 '23 07:01

Yuval Adam


2 Answers

To get only unique valid solutions, you can fix the orientation of the piece in the center. For example, you can assume that that the "1" on the piece in the center is always pointing "up".

If you're not already doing so, you can make your program much more efficient by checking for a valid solution after placing each piece. Once you've placed two pieces in an invalid way, you don't need to enumerate all of the other invalid combinations.

like image 87
Daniel Stutzbach Avatar answered Feb 08 '23 14:02

Daniel Stutzbach


If there were no piece in the centre, this would be easy. Simply consider only the situations where piece 0 is at the top.

But we can extend that idea to the actual situation. You can consider only the situations where piece i is in the centre, and piece (i+1) % 7 is at the top.

like image 29
Thomas Avatar answered Feb 08 '23 14:02

Thomas