constraint_solver: Add NQueensCp in all supported languages
This commit is contained in:
@@ -602,6 +602,7 @@ test_python_algorithms_samples: \
|
||||
|
||||
.PHONY: test_python_constraint_solver_samples # Run all Python CP Samples (located in ortools/constraint_solver/samples)
|
||||
test_python_constraint_solver_samples: \
|
||||
rpy_nqueens_cp \
|
||||
rpy_simple_cp_program \
|
||||
rpy_simple_routing_program \
|
||||
rpy_tsp \
|
||||
|
||||
102
ortools/constraint_solver/samples/NQueensCp.cs
Normal file
102
ortools/constraint_solver/samples/NQueensCp.cs
Normal file
@@ -0,0 +1,102 @@
|
||||
// Copyright 2010-2021 Google LLC
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// [START program]
|
||||
// OR-Tools solution to the N-queens problem.
|
||||
// [START import]
|
||||
using System;
|
||||
using Google.OrTools.ConstraintSolver;
|
||||
// [END import]
|
||||
|
||||
public class NQueensCp
|
||||
{
|
||||
public static void Main(String[] args)
|
||||
{
|
||||
// Instantiate the solver.
|
||||
// [START solver]
|
||||
Solver solver = new Solver("N-Queens");
|
||||
// [END solver]
|
||||
|
||||
// [START variables]
|
||||
const int BoardSize = 8;
|
||||
IntVar[] queens = new IntVar[BoardSize];
|
||||
for (int i = 0; i < BoardSize; ++i)
|
||||
{
|
||||
queens[i] = solver.MakeIntVar(0, BoardSize - 1, $"x{i}");
|
||||
}
|
||||
// [END variables]
|
||||
|
||||
// Define constraints.
|
||||
// [START constraints]
|
||||
// All rows must be different.
|
||||
solver.Add(queens.AllDifferent());
|
||||
|
||||
// All columns must be different because the indices of queens are all different.
|
||||
// No two queens can be on the same diagonal.
|
||||
IntVar[] diag1 = new IntVar[BoardSize];
|
||||
IntVar[] diag2 = new IntVar[BoardSize];
|
||||
for (int i = 0; i < BoardSize; ++i)
|
||||
{
|
||||
diag1[i] = solver.MakeSum(queens[i], i).Var();
|
||||
diag2[i] = solver.MakeSum(queens[i], -i).Var();
|
||||
}
|
||||
|
||||
solver.Add(diag1.AllDifferent());
|
||||
solver.Add(diag2.AllDifferent());
|
||||
// [END constraints]
|
||||
|
||||
// [START db]
|
||||
// Create the decision builder to search for solutions.
|
||||
DecisionBuilder db = solver.MakePhase(queens, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE);
|
||||
// [END db]
|
||||
|
||||
// [START solve]
|
||||
// Iterates through the solutions, displaying each.
|
||||
int SolutionCount = 0;
|
||||
solver.NewSearch(db);
|
||||
while (solver.NextSolution())
|
||||
{
|
||||
Console.WriteLine("Solution " + SolutionCount);
|
||||
for (int i = 0; i < BoardSize; ++i)
|
||||
{
|
||||
for (int j = 0; j < BoardSize; ++j)
|
||||
{
|
||||
if (queens[j].Value() == i)
|
||||
{
|
||||
Console.Write("Q");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.Write("_");
|
||||
}
|
||||
if (j != BoardSize - 1)
|
||||
Console.Write(" ");
|
||||
}
|
||||
Console.WriteLine("");
|
||||
}
|
||||
SolutionCount++;
|
||||
}
|
||||
solver.EndSearch();
|
||||
// [END solve]
|
||||
|
||||
// Statistics.
|
||||
// [START statistics]
|
||||
Console.WriteLine("Statistics");
|
||||
Console.WriteLine($" failures: {solver.Failures()}");
|
||||
Console.WriteLine($" branches: {solver.Branches()}");
|
||||
Console.WriteLine($" wall time: {solver.WallTime()} ms");
|
||||
Console.WriteLine($" Solutions found: {SolutionCount}");
|
||||
// [END statistics]
|
||||
}
|
||||
}
|
||||
// [END program]
|
||||
100
ortools/constraint_solver/samples/NQueensCp.java
Normal file
100
ortools/constraint_solver/samples/NQueensCp.java
Normal file
@@ -0,0 +1,100 @@
|
||||
// Copyright 2010-2021 Google LLC
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// [START program]
|
||||
// OR-Tools solution to the N-queens problem.
|
||||
package com.google.ortools.constraintsolver.samples;
|
||||
// [START import]
|
||||
// [END import]
|
||||
import com.google.ortools.Loader;
|
||||
import com.google.ortools.constraintsolver.DecisionBuilder;
|
||||
import com.google.ortools.constraintsolver.IntExpr;
|
||||
import com.google.ortools.constraintsolver.IntVar;
|
||||
import com.google.ortools.constraintsolver.Solver;
|
||||
import com.google.ortools.constraintsolver.main;
|
||||
// [END import]
|
||||
|
||||
/** N-Queens Problem. */
|
||||
public final class NQueensCp {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Loader.loadNativeLibraries();
|
||||
// Instantiate the solver.
|
||||
// [START solver]
|
||||
Solver solver = new Solver("N-Queens");
|
||||
// [END solver]
|
||||
|
||||
// [START variables]
|
||||
int boardSize = 8;
|
||||
IntVar[] queens = new IntVar[boardSize];
|
||||
for (int i = 0; i < boardSize; ++i) {
|
||||
queens[i] = solver.makeIntVar(0, boardSize - 1, "x" + i);
|
||||
}
|
||||
// [END variables]
|
||||
|
||||
// Define constraints.
|
||||
// [START constraints]
|
||||
// All rows must be different.
|
||||
solver.addConstraint(solver.makeAllDifferent(queens));
|
||||
|
||||
// All columns must be different because the indices of queens are all different.
|
||||
// No two queens can be on the same diagonal.
|
||||
IntVar[] diag1 = new IntVar[boardSize];
|
||||
IntVar[] diag2 = new IntVar[boardSize];
|
||||
for (int i = 0; i < boardSize; ++i) {
|
||||
diag1[i] = solver.makeSum(queens[i], i).var();
|
||||
diag2[i] = solver.makeSum(queens[i], -i).var();
|
||||
}
|
||||
solver.addConstraint(solver.makeAllDifferent(diag1));
|
||||
solver.addConstraint(solver.makeAllDifferent(diag2));
|
||||
// [END constraints]
|
||||
|
||||
// [START db]
|
||||
// Create the decision builder to search for solutions.
|
||||
final DecisionBuilder db =
|
||||
solver.makePhase(queens, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE);
|
||||
// [END db]
|
||||
|
||||
// [START solve]
|
||||
int solutionCount = 0;
|
||||
solver.newSearch(db);
|
||||
while (solver.nextSolution()) {
|
||||
System.out.println("Solution " + solutionCount);
|
||||
for (int i = 0; i < boardSize; ++i) {
|
||||
for (int j = 0; j < boardSize; ++j) {
|
||||
if (queens[j].value() == i) {
|
||||
System.out.print("Q");
|
||||
} else {
|
||||
System.out.print("_");
|
||||
}
|
||||
if (j != boardSize - 1)
|
||||
System.out.print(" ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
solutionCount++;
|
||||
}
|
||||
solver.endSearch();
|
||||
// [END solve]
|
||||
|
||||
// Statistics.
|
||||
// [START statistics]
|
||||
System.out.println("Statistics");
|
||||
System.out.println(" failures: " + solver.failures());
|
||||
System.out.println(" branches: " + solver.branches());
|
||||
System.out.println(" wall time: " + solver.wallTime() + "ms");
|
||||
System.out.println(" Solutions found: " + solutionCount);
|
||||
// [END statistics]
|
||||
}
|
||||
|
||||
private NQueensCp() {}
|
||||
}
|
||||
// [END program]
|
||||
112
ortools/constraint_solver/samples/nqueens_cp.cc
Normal file
112
ortools/constraint_solver/samples/nqueens_cp.cc
Normal file
@@ -0,0 +1,112 @@
|
||||
// Copyright 2011-2021 Google LLC
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// [START program]
|
||||
// OR-Tools solution to the N-queens problem.
|
||||
// [START import]
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
#include "ortools/constraint_solver/constraint_solver.h"
|
||||
// [END import]
|
||||
|
||||
namespace operations_research {
|
||||
|
||||
void NQueensCp(const int board_size) {
|
||||
// Instantiate the solver.
|
||||
// [START solver]
|
||||
Solver solver("N-Queens");
|
||||
// [END solver]
|
||||
|
||||
// [START variables]
|
||||
std::vector<IntVar*> queens;
|
||||
queens.reserve(board_size);
|
||||
for (int i=0; i < board_size; ++i) {
|
||||
queens.push_back(solver.MakeIntVar(0, board_size - 1, "x"+i));
|
||||
}
|
||||
// [END variables]
|
||||
|
||||
// Define constraints.
|
||||
// [START constraints]
|
||||
// The following sets the constraint that all queens are in different rows.
|
||||
solver.AddConstraint(solver.MakeAllDifferent(queens));
|
||||
|
||||
// All columns must be different because the indices of queens are all different.
|
||||
// No two queens can be on the same diagonal.
|
||||
std::vector<IntVar*> diag_1;
|
||||
diag_1.reserve(board_size);
|
||||
std::vector<IntVar*> diag_2;
|
||||
diag_2.reserve(board_size);
|
||||
for (int i=0; i < board_size; ++i) {
|
||||
diag_1.push_back(solver.MakeSum(queens[i], i)->Var());
|
||||
diag_2.push_back(solver.MakeSum(queens[i], -i)->Var());
|
||||
}
|
||||
solver.AddConstraint(solver.MakeAllDifferent(diag_1));
|
||||
solver.AddConstraint(solver.MakeAllDifferent(diag_2));
|
||||
// [END constraints]
|
||||
|
||||
// [START db]
|
||||
DecisionBuilder* const db = solver.MakePhase(
|
||||
queens, Solver::CHOOSE_FIRST_UNBOUND, Solver::ASSIGN_MIN_VALUE);
|
||||
// [END db]
|
||||
|
||||
// [START solve]
|
||||
// Iterates through the solutions, displaying each.
|
||||
int num_solutions = 0;
|
||||
|
||||
solver.NewSearch(db);
|
||||
while (solver.NextSolution()) {
|
||||
// Displays the solution just computed.
|
||||
LOG(INFO) << "Solution " << num_solutions;
|
||||
for (int i=0; i < board_size; ++i) {
|
||||
std::stringstream ss;
|
||||
for (int j=0; j < board_size; ++j) {
|
||||
if (queens[j]->Value() == i) {
|
||||
// There is a queen in column j, row i.
|
||||
ss << "Q";
|
||||
} else {
|
||||
ss << "_";
|
||||
}
|
||||
if (j != board_size-1) ss << " ";
|
||||
}
|
||||
LOG(INFO) << ss.str();
|
||||
}
|
||||
num_solutions++;
|
||||
}
|
||||
solver.EndSearch();
|
||||
// [END solve]
|
||||
|
||||
// Statistics.
|
||||
// [START statistics]
|
||||
LOG(INFO) << "Statistics";
|
||||
LOG(INFO) << " failures: " << solver.failures();
|
||||
LOG(INFO) << " branches: " << solver.branches();
|
||||
LOG(INFO) << " wall time: " << solver.wall_time() << " ms";
|
||||
LOG(INFO) << " Solutions found: " << num_solutions;
|
||||
// [END statistics]
|
||||
}
|
||||
|
||||
} // namespace operations_research
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
int board_size = 8;
|
||||
if (argc > 1) {
|
||||
board_size = std::atoi(argv[1]);
|
||||
}
|
||||
operations_research::NQueensCp(board_size);
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
// [END program]
|
||||
|
||||
85
ortools/constraint_solver/samples/nqueens_cp.py
Executable file
85
ortools/constraint_solver/samples/nqueens_cp.py
Executable file
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env python3
|
||||
# Copyright 2010-2021 Google LLC
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# [START program]
|
||||
"""OR-Tools solution to the N-queens problem."""
|
||||
# [START import]
|
||||
import sys
|
||||
from ortools.constraint_solver import pywrapcp
|
||||
# [END import]
|
||||
|
||||
|
||||
def main(board_size):
|
||||
# Creates the solver.
|
||||
# [START solver]
|
||||
solver = pywrapcp.Solver('n-queens')
|
||||
# [END solver]
|
||||
|
||||
# Creates the variables.
|
||||
# [START variables]
|
||||
# The array index is the column, and the value is the row.
|
||||
queens = [solver.IntVar(0, board_size - 1, f'x{i}') for i in range(board_size)]
|
||||
# [END variables]
|
||||
|
||||
# Creates the constraints.
|
||||
# [START constraints]
|
||||
# All rows must be different.
|
||||
solver.Add(solver.AllDifferent(queens))
|
||||
|
||||
# All columns must be different because the indices of queens are all different.
|
||||
# No two queens can be on the same diagonal.
|
||||
solver.Add(solver.AllDifferent([queens[i] + i for i in range(board_size)]))
|
||||
solver.Add(solver.AllDifferent([queens[i] - i for i in range(board_size)]))
|
||||
# [END constraints]
|
||||
|
||||
# [START db]
|
||||
db = solver.Phase(queens, solver.CHOOSE_FIRST_UNBOUND,
|
||||
solver.ASSIGN_MIN_VALUE)
|
||||
# [END db]
|
||||
|
||||
# [START solve]
|
||||
# Iterates through the solutions, displaying each.
|
||||
num_solutions = 0
|
||||
solver.NewSearch(db)
|
||||
while solver.NextSolution():
|
||||
# Displays the solution just computed.
|
||||
for i in range(board_size):
|
||||
for j in range(board_size):
|
||||
if queens[j].Value() == i:
|
||||
# There is a queen in column j, row i.
|
||||
print("Q", end=" ")
|
||||
else:
|
||||
print("_", end=" ")
|
||||
print()
|
||||
print()
|
||||
num_solutions += 1
|
||||
solver.EndSearch()
|
||||
# [END solve]
|
||||
|
||||
# Statistics.
|
||||
# [START statistics]
|
||||
print('\nStatistics')
|
||||
print(f' failures: {solver.Failures()}')
|
||||
print(f' branches: {solver.Branches()}')
|
||||
print(f' wall time: {solver.WallTime()} ms')
|
||||
print(f' Solutions found: {num_solutions}')
|
||||
# [END statistics]
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# By default, solve the 8x8 problem.
|
||||
board_size = 8
|
||||
if len(sys.argv) > 1:
|
||||
board_size = int(sys.argv[1])
|
||||
main(board_size)
|
||||
# [END program]
|
||||
Reference in New Issue
Block a user