Here is a very simple Constraint Programming problem:
If we see 56 legs and 20 heads, how many two-legged pheasants and four-legged rabbits are we looking at?
Here is some simple Constraint Programming code to find out:
void pheasant() {
Solver s("pheasant");
// Create integer variables to represent the number of pheasants and
// rabbits, with a minimum of 0 and a maximum of 20.
IntVar* const p = s.MakeIntVar(0, 20, "pheasant"));
IntVar* const r = s.MakeIntVar(0, 20, "rabbit"));
// The number of heads is the sum of pheasants and rabbits.
IntExpr* const heads = s.MakeSum(p, r);
// The number of legs is the sum of pheasants * 2 and rabbits * 4.
IntExpr* const legs = s.MakeSum(s.MakeProd(p, 2), s.MakeProd(r, 4));
// Constraints: the number of legs is 56 and heads is 20.
Constraint* const ct_legs = s.MakeEquality(legs, 56);
Constraint* const ct_heads = s.MakeEquality(heads, 20);
s.AddConstraint(ct_legs);
s.AddConstraint(ct_heads);
DecisionBuilder* const db = s.MakePhase(p, r,
Solver::CHOOSE_FIRST_UNBOUND,
Solver::ASSIGN_MIN_VALUE);
s.NewSearch(db);
CHECK(s.NextSolution());
LOG(INFO) << "rabbits -> " << r->Value() << ", pheasants -> "
<< p->Value();
LOG(INFO) << s.DebugString();
s.EndSearch();
}
which outputs:
rabbits -> 8, pheasants -> 12
Solver(name = "pheasant",
state = OUTSIDE_SEARCH,
branches = 0,
fails = 0,
decisions = 0
propagation loops = 11,
demons Run = 25,
Run time = 0 ms)
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2024-08-06 UTC."],[[["This documentation outlines the core objects and classes for Google's Operations Research constraint solver in C++."],["The constraint solver is a tool for tackling optimization problems by defining variables, constraints, and a search strategy to find feasible solutions."],["A simple example is provided, demonstrating how to solve a classic puzzle involving pheasants and rabbits using the constraint solver."],["A comprehensive list of available classes and their respective links to detailed documentation is included for reference."]]],["The document demonstrates constraint programming in C++ using a \"pheasant and rabbit\" problem. Integer variables represent the number of each animal. Constraints are set, defining the relationships between heads and legs. A solver finds a solution, assigning values to the variables, ultimately determining there are 8 rabbits and 12 pheasants. The code defines the variables, constraints, and a decision builder for the solver. It then displays the solution and solver statistics. The document outlines various classes within the C++ constraint solver library.\n"]]