mardi 26 avril 2016

N-Queens Display 1 Random Solution

So far I have this code that displays the 92 solutions for an 8x8 board for the N-Queens problem. Instead of displaying ALL 92 solutions, I am wanting to try and get it to just display 1 random solution each time it is ran. How can I do this?

import sys

from ortools.constraint_solver import pywrapcp

# by default, solve the 8x8 problem
n = 8 if len(sys.argv) < 2 else int(sys.argv[1])

# creates the solver
solver = pywrapcp.Solver("n-queens")

# creates the variables
# the array index is the row, and the value is the column
queens = [solver.IntVar(0, n - 1, "x%i" % i) for i in range(n)]
# creates the constraints

# all columns must be different
solver.Add(solver.AllDifferent(queens))

# no two queens can be on the same diagonal
solver.Add(solver.AllDifferent([queens[i] + i for i in range(n)]))
solver.Add(solver.AllDifferent([queens[i] - i for i in range(n)]))

# tells solver what to solve
db = solver.Phase(queens, solver.CHOOSE_MIN_SIZE_LOWEST_MAX, solver.ASSIGN_CENTER_VALUE)

solver.NewSearch(db)

# iterates through the solutions
num_solutions = 0
while solver.NextSolution():
  queen_columns = [int(queens[i].Value()) for i in range(n)]

  # displays the solutions
  for i in range(n):
    for j in range(n):
      if queen_columns[i] == j:
        print "Q",
      else:
        print "_",
    print
  print
  num_solutions += 1

solver.EndSearch()

print
print "Solutions found:", num_solutions




Aucun commentaire:

Enregistrer un commentaire