1 // Copyright 2010-2021 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 //     http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 package com.google.ortools.java;
14 
15 import com.google.ortools.Loader;
16 import com.google.ortools.constraintsolver.ConstraintSolverParameters;
17 import com.google.ortools.constraintsolver.DecisionBuilder;
18 import com.google.ortools.constraintsolver.IntVar;
19 import com.google.ortools.constraintsolver.Solver;
20 import java.util.logging.Logger;
21 
22 /** Sample showing how to model using the constraint programming solver.*/
23 public class RabbitsPheasants {
24   private static Logger logger = Logger.getLogger(RabbitsPheasants.class.getName());
25 
26   /**
27    * Solves the rabbits + pheasants problem.  We are seing 20 heads
28    * and 56 legs. How many rabbits and how many pheasants are we thus
29    * seeing?
30    */
solve(boolean traceSearch)31   private static void solve(boolean traceSearch) {
32     ConstraintSolverParameters parameters = ConstraintSolverParameters.newBuilder()
33                                                 .mergeFrom(Solver.defaultSolverParameters())
34                                                 .setTraceSearch(traceSearch)
35                                                 .build();
36     Solver solver = new Solver("RabbitsPheasants", parameters);
37     IntVar rabbits = solver.makeIntVar(0, 100, "rabbits");
38     IntVar pheasants = solver.makeIntVar(0, 100, "pheasants");
39     solver.addConstraint(solver.makeEquality(solver.makeSum(rabbits, pheasants), 20));
40     solver.addConstraint(solver.makeEquality(
41         solver.makeSum(solver.makeProd(rabbits, 4), solver.makeProd(pheasants, 2)), 56));
42     DecisionBuilder db =
43         solver.makePhase(rabbits, pheasants, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE);
44     solver.newSearch(db);
45     solver.nextSolution();
46     logger.info(rabbits.toString());
47     logger.info(pheasants.toString());
48     solver.endSearch();
49   }
50 
main(String[] args)51   public static void main(String[] args) throws Exception {
52     Loader.loadNativeLibraries();
53     boolean traceSearch = args.length > 0 && args[1].equals("--trace");
54     RabbitsPheasants.solve(traceSearch);
55   }
56 }
57