Files
ortools-clone/examples/notebook/sat/nqueens_sat.ipynb
Corentin Le Molgat 2cb9f320f6 notebook: update
2022-12-21 09:54:15 +01:00

168 lines
5.2 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "google",
"metadata": {},
"source": [
"##### Copyright 2022 Google LLC."
]
},
{
"cell_type": "markdown",
"id": "apache",
"metadata": {},
"source": [
"Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"you may not use this file except in compliance with the License.\n",
"You may obtain a copy of the License at\n",
"\n",
" http://www.apache.org/licenses/LICENSE-2.0\n",
"\n",
"Unless required by applicable law or agreed to in writing, software\n",
"distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"See the License for the specific language governing permissions and\n",
"limitations under the License.\n"
]
},
{
"cell_type": "markdown",
"id": "basename",
"metadata": {},
"source": [
"# nqueens_sat"
]
},
{
"cell_type": "markdown",
"id": "link",
"metadata": {},
"source": [
"<table align=\"left\">\n",
"<td>\n",
"<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/sat/nqueens_sat.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
"</td>\n",
"<td>\n",
"<a href=\"https://github.com/google/or-tools/blob/main/ortools/sat/samples/nqueens_sat.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
"</td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"id": "doc",
"metadata": {},
"source": [
"First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "install",
"metadata": {},
"outputs": [],
"source": [
"!pip install ortools"
]
},
{
"cell_type": "markdown",
"id": "description",
"metadata": {},
"source": [
"\n",
"OR-Tools solution to the N-queens problem."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "code",
"metadata": {},
"outputs": [],
"source": [
"import sys\n",
"import time\n",
"from ortools.sat.python import cp_model\n",
"\n",
"\n",
"class NQueenSolutionPrinter(cp_model.CpSolverSolutionCallback):\n",
" \"\"\"Print intermediate solutions.\"\"\"\n",
"\n",
" def __init__(self, queens):\n",
" cp_model.CpSolverSolutionCallback.__init__(self)\n",
" self.__queens = queens\n",
" self.__solution_count = 0\n",
" self.__start_time = time.time()\n",
"\n",
" def solution_count(self):\n",
" return self.__solution_count\n",
"\n",
" def on_solution_callback(self):\n",
" current_time = time.time()\n",
" print('Solution %i, time = %f s' %\n",
" (self.__solution_count, current_time - self.__start_time))\n",
" self.__solution_count += 1\n",
"\n",
" all_queens = range(len(self.__queens))\n",
" for i in all_queens:\n",
" for j in all_queens:\n",
" if self.Value(self.__queens[j]) == i:\n",
" # There is a queen in column j, row i.\n",
" print('Q', end=' ')\n",
" else:\n",
" print('_', end=' ')\n",
" print()\n",
" print()\n",
"\n",
"\n",
"\n",
"def main(board_size):\n",
" # Creates the solver.\n",
" model = cp_model.CpModel()\n",
"\n",
" # Creates the variables.\n",
" # There are `board_size` number of variables, one for a queen in each column\n",
" # of the board. The value of each variable is the row that the queen is in.\n",
" queens = [\n",
" model.NewIntVar(0, board_size - 1, 'x%i' % i) for i in range(board_size)\n",
" ]\n",
"\n",
" # Creates the constraints.\n",
" # All rows must be different.\n",
" model.AddAllDifferent(queens)\n",
"\n",
" # No two queens can be on the same diagonal.\n",
" model.AddAllDifferent(queens[i] + i for i in range(board_size))\n",
" model.AddAllDifferent(queens[i] - i for i in range(board_size))\n",
"\n",
" # Solve the model.\n",
" solver = cp_model.CpSolver()\n",
" solution_printer = NQueenSolutionPrinter(queens)\n",
" solver.parameters.enumerate_all_solutions = True\n",
" solver.Solve(model, solution_printer)\n",
"\n",
" # Statistics.\n",
" print('\\nStatistics')\n",
" print(f' conflicts : {solver.NumConflicts()}')\n",
" print(f' branches : {solver.NumBranches()}')\n",
" print(f' wall time : {solver.WallTime()} s')\n",
" print(f' solutions found: {solution_printer.solution_count()}')\n",
"\n",
"\n",
"# By default, solve the 8x8 problem.\n",
"size = 8\n",
"if len(sys.argv) > 1:\n",
" size = int(sys.argv[1])\n",
"main(size)\n",
"\n"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}