Add Simple Cp Program

This commit is contained in:
Corentin Le Molgat
2019-03-14 12:58:56 +01:00
parent 4e0d93be07
commit 57f7ef8464
8 changed files with 265 additions and 15 deletions

View File

@@ -368,6 +368,7 @@ test_cc_constraint_solver_samples: \
rcc_nurses_cp \
rcc_rabbits_and_pheasants_cp \
rcc_simple_ls_program \
rcc_simple_cp_program \
rcc_simple_routing_program \
rcc_tsp \
rcc_tsp_cities \

View File

@@ -440,6 +440,7 @@ test_dotnet_algorithms_samples: ;
.PHONY: test_dotnet_constraint_solver_samples # Build and Run all .Net CP Samples (located in ortools/constraint_solver/samples)
test_dotnet_constraint_solver_samples:
$(MAKE) run SOURCE=ortools/constraint_solver/samples/SimpleCpProgram.cs
$(MAKE) run SOURCE=ortools/constraint_solver/samples/SimpleRoutingProgram.cs
$(MAKE) run SOURCE=ortools/constraint_solver/samples/Tsp.cs
$(MAKE) run SOURCE=ortools/constraint_solver/samples/TspCities.cs

View File

@@ -373,6 +373,7 @@ test_java_algorithms_samples: \
.PHONY: test_java_constraint_solver_samples # Build and Run all Java CP Samples (located in ortools/constraint_solver/samples)
test_java_constraint_solver_samples: \
rjava_SimpleCpProgram \
rjava_SimpleRoutingProgram \
rjava_Tsp \
rjava_TspCities \

View File

@@ -0,0 +1,71 @@
// Copyright 2010-2018 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]
// [START import]
using System;
using Google.OrTools.ConstraintSolver;
// [END import]
/// <summary>
/// This is a simple CP program.
/// </summary>
public class SimpleCpProgram {
public static void Main(String[] args) {
// Instantiate the solver.
// [START solver]
Solver solver = new Solver("CpSimple");
// [END solver]
// Create the variables.
// [START variables]
const long numVals = 3;
IntVar x = solver.MakeIntVar(0, numVals - 1, "x");
IntVar y = solver.MakeIntVar(0, numVals - 1, "y");
IntVar z = solver.MakeIntVar(0, numVals - 1, "z");
// [END variables]
// Constraint 0: x != y..
// [START constraints]
solver.Add(solver.MakeAllDifferent(new IntVar[]{x, y}));
Console.WriteLine($"Number of constraints: {solver.Constraints()}");
// [END constraints]
// Solve the problem.
// [START solve]
DecisionBuilder db = solver.MakePhase(
new IntVar[]{x, y, z},
Solver.CHOOSE_FIRST_UNBOUND,
Solver.ASSIGN_MIN_VALUE);
// [END solve]
// Print solution on console.
// [START print_solution]
int count = 0;
solver.NewSearch(db);
while (solver.NextSolution()) {
++count;
Console.WriteLine($"Solution: {count}\n x={x.Value()} y={y.Value()} z={z.Value()}");
}
solver.EndSearch();
Console.WriteLine($"Number of solutions found: {solver.Solutions()}");
// [END print_solution]
// [START advanced]
Console.WriteLine("Advanced usage:");
Console.WriteLine($"Problem solved in {solver.WallTime()}ms");
Console.WriteLine($"Memory usage: {Solver.MemoryUsage()}bytes");
// [END advanced]
}
}
// [END program]

View File

@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<LangVersion>7.2</LangVersion>
<TargetFramework>netcoreapp2.1</TargetFramework>
<EnableDefaultItems>false</EnableDefaultItems>
<RestoreSources>../../../packages;$(RestoreSources);https://api.nuget.org/v3/index.json</RestoreSources>
<AssemblyName>Google.OrTools.SimpleCpProgram</AssemblyName>
<IsPackable>true</IsPackable>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugType>full</DebugType>
<Optimize>true</Optimize>
<GenerateTailCalls>true</GenerateTailCalls>
</PropertyGroup>
<ItemGroup>
<Compile Include="SimpleCpProgram.cs" />
<PackageReference Include="Google.OrTools" Version="7.0*" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,75 @@
// Copyright 2010-2018 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]
// [START import]
import com.google.ortools.constraintsolver.DecisionBuilder;
import com.google.ortools.constraintsolver.IntVar;
import com.google.ortools.constraintsolver.Solver;
import java.util.logging.Logger;
// [END import]
/** Simple CP Program.*/
public class SimpleCpProgram {
static {
System.loadLibrary("jniortools");
}
private static final Logger logger = Logger.getLogger(SimpleCpProgram.class.getName());
public static void main(String[] args) throws Exception {
// Instantiate the solver.
// [START solver]
Solver solver = new Solver("CpSimple");
// [END solver]
// Create the variables.
// [START variables]
final long numVals = 3;
final IntVar x = solver.makeIntVar(0, numVals - 1, "x");
final IntVar y = solver.makeIntVar(0, numVals - 1, "y");
final IntVar z = solver.makeIntVar(0, numVals - 1, "z");
// [END variables]
// Constraint 0: x != y..
// [START constraints]
solver.addConstraint(solver.makeAllDifferent(new IntVar[] {x, y}));
logger.info("Number of constraints: " + solver.constraints());
// [END constraints]
// Solve the problem.
// [START solve]
final DecisionBuilder db = solver.makePhase(
new IntVar[] {x, y, z}, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE);
// [END solve]
// Print solution on console.
// [START print_solution]
int count = 0;
solver.newSearch(db);
while (solver.nextSolution()) {
++count;
logger.info(
String.format("Solution: %d\n x=%d y=%d z=%d", count, x.value(), y.value(), z.value()));
}
solver.endSearch();
logger.info("Number of solutions found: " + solver.solutions());
// [END print_solution]
// [START advanced]
logger.info(String.format("Advanced usage:\nProblem solved in %d ms\nMemory usage: %d bytes",
solver.wallTime(), Solver.memoryUsage()));
// [END advanced]
}
}
// [END program]

View File

@@ -0,0 +1,77 @@
// Copyright 2010-2018 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]
// [START import]
#include "ortools/constraint_solver/constraint_solver.h"
// [END import]
namespace operations_research {
void SimpleCpProgram() {
// Instantiate the solver.
// [START solver]
Solver solver("CpSimple");
// [END solver]
// Create the variables.
// [START variables]
const int64 num_vals = 3;
IntVar* const x = solver.MakeIntVar(0, num_vals - 1, "x");
IntVar* const y = solver.MakeIntVar(0, num_vals - 1, "y");
IntVar* const z = solver.MakeIntVar(0, num_vals - 1, "z");
// [END variables]
// Constraint 0: x != y..
// [START constraints]
solver.AddConstraint(solver.MakeAllDifferent({x, y}));
LOG(INFO) << "Number of constraints: "
<< std::to_string(solver.constraints());
// [END constraints]
// Solve the problem.
// [START solve]
DecisionBuilder* const db = solver.MakePhase(
{x, y, z}, Solver::CHOOSE_FIRST_UNBOUND, Solver::ASSIGN_MIN_VALUE);
// [END solve]
// Print solution on console.
// [START print_solution]
int count = 0;
solver.NewSearch(db);
while (solver.NextSolution()) {
++count;
LOG(INFO) << "Solution " << count << ":" << std::endl
<< " x=" << x->Value() << " y=" << y->Value()
<< " z=" << z->Value();
}
solver.EndSearch();
LOG(INFO) << "Number of solutions found: " << solver.solutions();
// [END print_solution]
// [START advanced]
LOG(INFO) << "Advanced usage:" << std::endl
<< "Problem solved in " << std::to_string(solver.wall_time())
<< "ms" << std::endl
<< "Memory usage: " << std::to_string(Solver::MemoryUsage())
<< "bytes";
// [END advanced]
}
} // namespace operations_research
int main(int argc, char** argv) {
operations_research::SimpleCpProgram();
return EXIT_SUCCESS;
}
// [END program]

View File

@@ -1,6 +1,4 @@
#!/usr/bin/env python
# This Python file uses the following encoding: utf-8
# Copyright 2018 Google LLC
# Copyright 2010-2018 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
@@ -18,13 +16,15 @@
# [START import]
from __future__ import print_function
from ortools.constraint_solver import pywrapcp
# [END import]
def main():
"""Entry point of the program"""
"""Entry point of the program."""
# Instantiate the solver.
# [START solver]
solver = pywrapcp.Solver('ConstraintExample')
solver = pywrapcp.Solver('CPSimple')
# [END solver]
# Create the variables.
@@ -38,34 +38,36 @@ def main():
# Constraint 0: x != y.
# [START constraints]
solver.Add(x != y)
print('Number of constraints =', solver.Constraints())
print('Number of constraints: ', solver.Constraints())
# [END constraints]
# Call the solver.
# Solve the problem.
# [START solve]
decision_builder = solver.Phase([x, y, z], solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
# [END solve]
# Print solution on console.
# [START print_solution]
count = 0
solver.NewSearch(decision_builder)
while solver.NextSolution():
solution = 'Solution:'
count += 1
solution = 'Solution {}:\n'.format(count)
for var in [x, y, z]:
solution += ' {} = {};'.format(var.Name(), var.Value())
solution += ' {} = {}'.format(var.Name(), var.Value())
print(solution)
solver.EndSearch()
print("Number of solutions found:", solver.Solutions())
print('Number of solutions found: ', count)
# [END print_solution]
# [START advanced]
print('\nAdvanced usage:')
print('Problem solved in ', solver.WallTime(), ' milliseconds')
print('Memory usage: ', pywrapcp.Solver.MemoryUsage(), ' bytes')
print('Advanced usage:')
print('Problem solved in ', solver.WallTime(), 'ms')
print('Memory usage: ', pywrapcp.Solver.MemoryUsage(), 'bytes')
# [END advanced]
if __name__ == "__main__":
if __name__ == '__main__':
main()
# [END program]