2016-06-18 10 views
0

N-Queens Puzzleの各ソリューションをリストに保存しようとしています。しかし、各リストをサブリストとして追加しようとすると、10個の個別ソリューションとは対照的に、最後のソリューションのみがリストに追加されます(10回)。私の目標は、私がボードを走らせるたびに、まだ発見されていない新しいソリューションだけが印刷され、リストに追加されるようにすることです。クイーンズパズルにそれぞれのユニークな解を付けてリストを追加します。最後の解決策がリストに追加された唯一の解決策である理由はわかりません。

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. 
+0

'.append(BD)'それはまた、コンテンツを変更し、そのリストが変化した場合、元のリストへの参照を格納します'solutions'に追加して、その時点でコピーを作成して' .append(list(bd)) 'に変更するだけです。 –

答えて

0

ちょうどあなたの現在のソリューションのコピーを作成します

solutions.append(list(bd)) 

solutions.append(bd) 

を変更。 結果リストにbdへの参照を追加するが、後でリストbdをシャッフルするので、リスト内で同じソリューションを10回繰り返すことに問題があります。重複の解決策は、変更をスキップするために

if not has_clashes(bd): 

if not has_clashes(bd) and bd not in solutions: 
関連する問題