ส่วนนี้จะอธิบายโปรแกรมแก้โจทย์ปัญหาดั้งเดิม ซึ่งแทนที่ด้วยโปรแกรมแก้โจทย์ CP-SAT ที่เหนือกว่า
ส่วนต่อไปนี้จะอธิบายวิธีแก้ตัวอย่างที่อธิบายไว้ในส่วน CP-SAT โดยคราวนี้ใช้เครื่องมือแก้โจทย์ CP เดิม หากคุณยังยืนยันที่จะใช้ตัวแก้โจทย์ CP เดิม คุณสามารถเรียกดูเอกสารอ้างอิง API ได้ โปรดทราบว่าเครื่องมือแก้โจทย์ CP เดิมเป็นพื้นฐานของไลบรารีการกำหนดเส้นทาง และ API ของเครื่องมือแก้โจทย์ CP อาจจำเป็นต่อการปรับแต่งโมเดลการกำหนดเส้นทาง
นำเข้าไลบรารี
โค้ดต่อไปนี้จะนำเข้าไลบรารีที่จำเป็น
Python
from ortools.constraint_solver import pywrapcp
C++
#include <ostream> #include <string> #include "ortools/constraint_solver/constraint_solver.h"
Java
import com.google.ortools.Loader; import com.google.ortools.constraintsolver.DecisionBuilder; import com.google.ortools.constraintsolver.IntVar; import com.google.ortools.constraintsolver.Solver; import java.util.logging.Logger;
C#
using System; using Google.OrTools.ConstraintSolver;
ประกาศเครื่องมือแก้โจทย์
โค้ดต่อไปนี้จะประกาศเครื่องมือแก้โจทย์
Python
solver = pywrapcp.Solver("CPSimple")
C++
Solver solver("CpSimple");
Java
Solver solver = new Solver("CpSimple");
C#
Solver solver = new Solver("CpSimple");
สร้างตัวแปร
โค้ดต่อไปนี้จะสร้างตัวแปรของปัญหา
เครื่องมือแก้โจทย์จะสร้างตัวแปร 3 ตัว ได้แก่ x, y และ z โดยแต่ละตัวสามารถรับค่า 0, 1 หรือ 2
Python
num_vals = 3 x = solver.IntVar(0, num_vals - 1, "x") y = solver.IntVar(0, num_vals - 1, "y") z = solver.IntVar(0, num_vals - 1, "z")
C++
const int64_t 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");
Java
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");
C#
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");
สร้างข้อจำกัด
โค้ดต่อไปนี้จะสร้างข้อจำกัด x ≠ y
Python
solver.Add(x != y)
print("Number of constraints: ", solver.Constraints())
C++
solver.AddConstraint(solver.MakeAllDifferent({x, y}));
LOG(INFO) << "Number of constraints: "
<< std::to_string(solver.constraints());
Java
solver.addConstraint(solver.makeAllDifferent(new IntVar[] {x, y}));
logger.info("Number of constraints: " + solver.constraints());
C#
solver.Add(solver.MakeAllDifferent(new IntVar[] { x, y }));
Console.WriteLine($"Number of constraints: {solver.Constraints()}");
เรียกเครื่องมือแก้โจทย์
โค้ดต่อไปนี้จะเรียกตัวแก้โจทย์
เครื่องมือสร้างการตัดสินใจคืออินพุตหลักสำหรับเครื่องมือแก้โจทย์ CP เดิม ซึ่งประกอบด้วยข้อมูลต่อไปนี้
vars— อาร์เรย์ที่มีตัวแปรของโจทย์- กฎสำหรับเลือกตัวแปรถัดไปที่จะกําหนดค่า
- กฎสำหรับเลือกค่าถัดไปที่จะกําหนดให้กับตัวแปรนั้น
โปรดดูรายละเอียดในเครื่องมือสร้างคำตัดสิน
Python
decision_builder = solver.Phase(
[x, y, z], solver.CHOOSE_FIRST_UNBOUND, solver.ASSIGN_MIN_VALUE
)
C++
DecisionBuilder* const db = solver.MakePhase(
{x, y, z}, Solver::CHOOSE_FIRST_UNBOUND, Solver::ASSIGN_MIN_VALUE);
Java
final DecisionBuilder db = solver.makePhase(
new IntVar[] {x, y, z}, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE);
C#
DecisionBuilder db =
solver.MakePhase(new IntVar[] { x, y, z }, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE);
พิมพ์โซลูชัน
โค้ดสำหรับเครื่องพิมพ์โซลูชัน ซึ่งแสดงแต่ละโซลูชันเมื่อเครื่องมือแก้โจทย์พบ แสดงในส่วนต่อไป
เนื่องจากมีวิธีแก้ปัญหามากกว่า 1 วิธี ทำให้เราสามารถทำซ้ำการแก้ปัญหาด้วยลูป while solver.NextSolution() (โปรดทราบว่าวิธีนี้ทำงานแตกต่างจากเครื่องพิมพ์โซลูชันสำหรับเครื่องมือแก้โจทย์ CP-SAT)
Python
count = 0
solver.NewSearch(decision_builder)
while solver.NextSolution():
count += 1
solution = f"Solution {count}:\n"
for var in [x, y, z]:
solution += f" {var.Name()} = {var.Value()}"
print(solution)
solver.EndSearch()
print(f"Number of solutions found: {count}")
C++
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();
Java
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());
C#
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()}");
ผลลัพธ์ที่แสดงโดยเครื่องมือแก้โจทย์
วิธีแก้ไข 18 ข้อที่เครื่องมือแก้โจทย์พบมีดังนี้
Number of constraints: 1 Solution 1: x = 0 y = 1 z = 0 Solution 2: x = 0 y = 1 z = 1 Solution 3: x = 0 y = 1 z = 2 Solution 4: x = 0 y = 2 z = 0 Solution 5: x = 0 y = 2 z = 1 Solution 6: x = 0 y = 2 z = 2 Solution 7: x = 1 y = 0 z = 0 Solution 8: x = 1 y = 0 z = 1 Solution 9: x = 1 y = 0 z = 2 Solution 10: x = 1 y = 2 z = 0 Solution 11: x = 1 y = 2 z = 1 Solution 12: x = 1 y = 2 z = 2 Solution 13: x = 2 y = 0 z = 0 Solution 14: x = 2 y = 0 z = 1 Solution 15: x = 2 y = 0 z = 2 Solution 16: x = 2 y = 1 z = 0 Solution 17: x = 2 y = 1 z = 1 Solution 18: x = 2 y = 1 z = 2 Number of solutions found: 18 Advanced usage: Problem solved in 2 ms Memory usage: 13918208 bytes
ดำเนินการตามโปรแกรมสำเร็จ
ต่อไปนี้คือโปรแกรมที่สมบูรณ์สำหรับตัวอย่างที่ใช้เครื่องมือแก้โจทย์ CP เดิม
Python
"""Simple Constraint optimization example."""
from ortools.constraint_solver import pywrapcp
def main():
"""Entry point of the program."""
# Instantiate the solver.
solver = pywrapcp.Solver("CPSimple")
# Create the variables.
num_vals = 3
x = solver.IntVar(0, num_vals - 1, "x")
y = solver.IntVar(0, num_vals - 1, "y")
z = solver.IntVar(0, num_vals - 1, "z")
# Constraint 0: x != y.
solver.Add(x != y)
print("Number of constraints: ", solver.Constraints())
# Solve the problem.
decision_builder = solver.Phase(
[x, y, z], solver.CHOOSE_FIRST_UNBOUND, solver.ASSIGN_MIN_VALUE
)
# Print solution on console.
count = 0
solver.NewSearch(decision_builder)
while solver.NextSolution():
count += 1
solution = f"Solution {count}:\n"
for var in [x, y, z]:
solution += f" {var.Name()} = {var.Value()}"
print(solution)
solver.EndSearch()
print(f"Number of solutions found: {count}")
print("Advanced usage:")
print(f"Problem solved in {solver.WallTime()}ms")
print(f"Memory usage: {pywrapcp.Solver.MemoryUsage()}bytes")
if __name__ == "__main__":
main()
C++
#include <ostream>
#include <string>
#include "ortools/constraint_solver/constraint_solver.h"
namespace operations_research {
void SimpleCpProgram() {
// Instantiate the solver.
Solver solver("CpSimple");
// Create the variables.
const int64_t 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");
// Constraint 0: x != y..
solver.AddConstraint(solver.MakeAllDifferent({x, y}));
LOG(INFO) << "Number of constraints: "
<< std::to_string(solver.constraints());
// Solve the problem.
DecisionBuilder* const db = solver.MakePhase(
{x, y, z}, Solver::CHOOSE_FIRST_UNBOUND, Solver::ASSIGN_MIN_VALUE);
// Print solution on console.
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();
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";
}
} // namespace operations_research
int main(int /*argc*/, char* /*argv*/[]) {
operations_research::SimpleCpProgram();
return EXIT_SUCCESS;
}
Java
package com.google.ortools.constraintsolver.samples;
import com.google.ortools.Loader;
import com.google.ortools.constraintsolver.DecisionBuilder;
import com.google.ortools.constraintsolver.IntVar;
import com.google.ortools.constraintsolver.Solver;
import java.util.logging.Logger;
/** Simple CP Program.*/
public class SimpleCpProgram {
private SimpleCpProgram() {}
private static final Logger logger = Logger.getLogger(SimpleCpProgram.class.getName());
public static void main(String[] args) throws Exception {
Loader.loadNativeLibraries();
// Instantiate the solver.
Solver solver = new Solver("CpSimple");
// Create the 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");
// Constraint 0: x != y..
solver.addConstraint(solver.makeAllDifferent(new IntVar[] {x, y}));
logger.info("Number of constraints: " + solver.constraints());
// Solve the problem.
final DecisionBuilder db = solver.makePhase(
new IntVar[] {x, y, z}, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE);
// Print solution on console.
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());
logger.info(String.format("Advanced usage:\nProblem solved in %d ms\nMemory usage: %d bytes",
solver.wallTime(), Solver.memoryUsage()));
}
}
C#
using System;
using Google.OrTools.ConstraintSolver;
/// <summary>
/// This is a simple CP program.
/// </summary>
public class SimpleCpProgram
{
public static void Main(String[] args)
{
// Instantiate the solver.
Solver solver = new Solver("CpSimple");
// Create the 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");
// Constraint 0: x != y..
solver.Add(solver.MakeAllDifferent(new IntVar[] { x, y }));
Console.WriteLine($"Number of constraints: {solver.Constraints()}");
// Solve the problem.
DecisionBuilder db =
solver.MakePhase(new IntVar[] { x, y, z }, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE);
// Print solution on console.
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()}");
Console.WriteLine("Advanced usage:");
Console.WriteLine($"Problem solved in {solver.WallTime()}ms");
Console.WriteLine($"Memory usage: {Solver.MemoryUsage()}bytes");
}
}
เครื่องมือสร้างการตัดสินใจ
ข้อมูลหลักที่ไปยังเครื่องมือแก้โจทย์ CP เดิมคือเครื่องมือสร้างการตัดสินใจ ซึ่งมีตัวแปรของโจทย์และตั้งค่าตัวเลือกสำหรับเครื่องมือแก้โจทย์คณ
ตัวอย่างโค้ดในส่วนก่อนหน้าสร้างตัวสร้างการตัดสินใจโดยใช้เมธอด Phase (สอดคล้องกับเมธอด C++ MakePhase
คำว่าระยะหมายถึงระยะของการค้นหา ตัวอย่างง่ายๆ นี้มีเพียงระยะเดียว แต่สำหรับปัญหาที่ซับซ้อนมากขึ้น เครื่องมือสร้างการตัดสินใจอาจมีมากกว่า 1 เฟส เพื่อให้เครื่องมือแก้โจทย์สามารถใช้กลยุทธ์การค้นหาที่แตกต่างกันจากระยะหนึ่งไปยังอีกระยะได้
เมธอด Phase มีพารามิเตอร์อินพุต 3 พารามิเตอร์ ได้แก่
vars— อาร์เรย์ที่มีตัวแปรของโจทย์ ซึ่งในกรณีนี้คือ[x, y, z]IntVarStrategy— กฎสำหรับการเลือกตัวแปรที่ไม่มีการเชื่อมโยงถัดไปเพื่อกำหนดค่า ในตัวอย่างนี้ โค้ดจะใช้CHOOSE_FIRST_UNBOUNDเริ่มต้น ซึ่งหมายความว่าในแต่ละขั้นตอน เครื่องมือแก้โจทย์จะเลือกตัวแปรแรกที่ไม่มีการเชื่อมโยงตามลำดับที่เกิดขึ้นในอาร์เรย์ตัวแปรที่ส่งไปยังเมธอดPhaseIntValueStrategy— กฎสำหรับการเลือกค่าถัดไปที่จะกำหนดให้ตัวแปร โค้ดนี้จะใช้ASSIGN_MIN_VALUEเริ่มต้น ซึ่งจะเลือกค่าที่น้อยที่สุดที่ยังไม่ได้ลองใช้กับตัวแปรนี้ ซึ่งจะเป็นการกำหนดค่า ตามลำดับที่เพิ่มขึ้น อีกตัวเลือกหนึ่งคือASSIGN_MAX_VALUEซึ่งในกรณีนี้เครื่องมือแก้โจทย์จะกำหนดค่าจากมากไปน้อย