Generating all unique combinations for "drive ya nuts" puzzle

Posted by Yuval A on Stack Overflow See other posts from Stack Overflow or by Yuval A
Published on 2010-04-08T14:54:16Z Indexed on 2010/04/08 15:03 UTC
Read the original article Hit count: 469

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

alt text

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?

© Stack Overflow or respective owner

Related posts about language-agnostic

Related posts about python