Search code examples
pythonn-queens

Appending the list with each unique solution to the Queens Puzzle. I don't know why the last solution is the only solution appended to the list?


I am trying to save each individual solution to the N-Queens Puzzle to a list. However, when I try to add each list as a sub-list, only the last solution is added to the list (10 times), as opposed to the 10 individual solutions. My goal is to ensure that each time I run the board only new solutions, which have not been found already, are printed and added to the list.

def share_diagonal(x0, y0, x1, y1):
    """ Is (x0, y) on the same shared diagonal with (x1, y1)? """
    dx = abs(x1 - x0)  # Calc the absolute y distance
    dy = abs(y1 - y0)  # Calc the absolute x distance
    return dx == dy  # They clash if dx == yx


def col_clashes(bs, c):
    """ Return True if the queen at column c clashes
        with any queen to its left.
    """
    for i in range(c):  # Look at all columns to the left of c
        if share_diagonal(i, bs[i], c, bs[c]):
            return True
    return False  # No clashes - col c has a safe placement


def has_clashes(the_board):
    """ Determine whether we have any queens clashing on the diagonal.
        We're assuming here that the_board is a permutation of column
        numbers, so we're not explicitly checking row or column clashes.
    """
    for col in range(1, len(the_board)):
        if col_clashes(the_board, col):
            return True
    return False

solutions = []

def main(board_size):
    import random
    global solutions
    rng = random.Random()  # Instantiate a generator

    bd = list(range(board_size))  # Generate the initial permutation
    num_found = 0
    tries = 0
    while num_found < 10:
        rng.shuffle(bd)
        tries += 1
        if not has_clashes(bd):
            print("Found solution {0} in {1} tries.".format(bd, tries))
            solutions.append(bd)  # This is the section in which I am trying to save each individual solution into a list. 
            tries = 0
            num_found += 1


main(8)
for i in solutions:
    print(i)  # When I print off the list, all items in the list are replica's of the last solution found. Not each individual solution. I don't know why this is occurring.

Solution

  • Just change

    solutions.append(bd)
    

    to

    solutions.append(list(bd))
    

    which creates a copy of your current solution. Your problem with having the same solution 10 times in the list is because you add a reference to bd in your result list but shuffle the list bd in-place afterwards.

    In order to skip duplicate solutions change

    if not has_clashes(bd):
    

    to

    if not has_clashes(bd) and bd not in solutions: