当前位置: 首页>>代码示例>>C#>>正文


C# Solver.Add方法代码示例

本文整理汇总了C#中Solver.Add方法的典型用法代码示例。如果您正苦于以下问题:C# Solver.Add方法的具体用法?C# Solver.Add怎么用?C# Solver.Add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Solver的用法示例。


在下文中一共展示了Solver.Add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: MyCumulative

  /*
   * Decompositon of cumulative.
   *
   * Inspired by the MiniZinc implementation:
   * http://www.g12.csse.unimelb.edu.au/wiki/doku.php?id=g12:zinc:lib:minizinc:std:cumulative.mzn&s[]=cumulative
   * The MiniZinc decomposition is discussed in the paper:
   * A. Schutt, T. Feydy, P.J. Stuckey, and M. G. Wallace.
   * "Why cumulative decomposition is not as bad as it sounds."
   * Download:
   * http://www.cs.mu.oz.au/%7Epjs/rcpsp/papers/cp09-cu.pdf
   * http://www.cs.mu.oz.au/%7Epjs/rcpsp/cumu_lazyfd.pdf
   *
   *
   * Parameters:
   *
   * s: start_times    assumption: IntVar[]
   * d: durations      assumption: int[]
   * r: resources      assumption: int[]
   * b: resource limit assumption: IntVar or int
   *
   *
   */
  static void MyCumulative(Solver solver,
                           IntVar[] s,
                           int[] d,
                           int[] r,
                           IntVar b) {

    int[] tasks = (from i in Enumerable.Range(0, s.Length)
                   where r[i] > 0 && d[i] > 0
                   select i).ToArray();
    int times_min = tasks.Min(i => (int)s[i].Min());
    int d_max = d.Max();
    int times_max = tasks.Max(i => (int)s[i].Max() + d_max);
    for(int t = times_min; t <= times_max; t++) {
      ArrayList bb = new ArrayList();
      foreach(int i in tasks) {
        bb.Add(((s[i] <= t) * (s[i] + d[i]> t) * r[i]).Var());
      }
      solver.Add((bb.ToArray(typeof(IntVar)) as IntVar[]).Sum() <= b);
    }

    // Somewhat experimental:
    // This constraint is needed to constrain the upper limit of b.
    if (b is IntVar) {
      solver.Add(b <= r.Sum());
    }

   }
开发者ID:RickOne16,项目名称:or-tools,代码行数:49,代码来源:furniture_moving.cs

示例2: Solve

  /**
   *
   * Solve the Least diff problem
   * For more info, see http://www.hakank.org/google_or_tools/least_diff.py
   *
   */
  private static void Solve()
  {
    Solver solver = new Solver("LeastDiff");

    //
    // Decision variables
    //
    IntVar A = solver.MakeIntVar(0, 9, "A");
    IntVar B = solver.MakeIntVar(0, 9, "B");
    IntVar C = solver.MakeIntVar(0, 9, "C");
    IntVar D = solver.MakeIntVar(0, 9, "D");
    IntVar E = solver.MakeIntVar(0, 9, "E");
    IntVar F = solver.MakeIntVar(0, 9, "F");
    IntVar G = solver.MakeIntVar(0, 9, "G");
    IntVar H = solver.MakeIntVar(0, 9, "H");
    IntVar I = solver.MakeIntVar(0, 9, "I");
    IntVar J = solver.MakeIntVar(0, 9, "J");

    IntVar[] all = new IntVar[] {A,B,C,D,E,F,G,H,I,J};
    int[] coeffs = {10000,1000,100,10,1};
    IntVar x = new IntVar[]{A,B,C,D,E}.ScalProd(coeffs).Var();
    IntVar y = new IntVar[]{F,G,H,I,J}.ScalProd(coeffs).Var();
    IntVar diff = (x - y).VarWithName("diff");


    //
    // Constraints
    //
    solver.Add(all.AllDifferent());
    solver.Add(A > 0);
    solver.Add(F > 0);
    solver.Add(diff > 0);


    //
    // Objective
    //
    OptimizeVar obj = diff.Minimize(1);

    //
    // Search
    //
    DecisionBuilder db = solver.MakePhase(all,
                                          Solver.CHOOSE_PATH,
                                          Solver.ASSIGN_MIN_VALUE);

    solver.NewSearch(db, obj);
    while (solver.NextSolution()) {
      Console.WriteLine("{0} - {1} = {2}  ({3}",x.Value(), y.Value(), diff.Value(), diff.ToString());
    }

    Console.WriteLine("\nSolutions: {0}", solver.Solutions());
    Console.WriteLine("WallTime: {0}ms", solver.WallTime());
    Console.WriteLine("Failures: {0}", solver.Failures());
    Console.WriteLine("Branches: {0} ", solver.Branches());

    solver.EndSearch();

  }
开发者ID:RickOne16,项目名称:or-tools,代码行数:65,代码来源:least_diff.cs

示例3: CPisFun

    //  We don't need helper functions here
    //  Csharp syntax is easier than C++ syntax!

    private static void CPisFun (int kBase)
    {
        //  Constraint Programming engine
        Solver solver = new Solver ("CP is fun!");

        // Decision variables
        IntVar c = solver.MakeIntVar (1, kBase - 1, "C");
        IntVar p = solver.MakeIntVar (0, kBase - 1, "P");
        IntVar i = solver.MakeIntVar (1, kBase - 1, "I");
        IntVar s = solver.MakeIntVar (0, kBase - 1, "S");
        IntVar f = solver.MakeIntVar (1, kBase - 1, "F");
        IntVar u = solver.MakeIntVar (0, kBase - 1, "U");
        IntVar n = solver.MakeIntVar (0, kBase - 1, "N");
        IntVar t = solver.MakeIntVar (1, kBase - 1, "T");
        IntVar r = solver.MakeIntVar (0, kBase - 1, "R");
        IntVar e = solver.MakeIntVar (0, kBase - 1, "E");

        // We need to group variables in a vector to be able to use
        // the global constraint AllDifferent
        IntVar[] letters = new IntVar[] { c, p, i, s, f, u, n, t, r, e};

        // Check if we have enough digits
        if (kBase < letters.Length) {
          throw new Exception("kBase < letters.Length");
        }

        //  Constraints
        solver.Add (letters.AllDifferent ());

        // CP + IS + FUN = TRUE
        solver.Add (p + s + n + kBase * (c + i + u) + kBase * kBase * f ==
               e + kBase * u + kBase * kBase * r + kBase * kBase * kBase * t);

        SolutionCollector all_solutions = solver.MakeAllSolutionCollector();
        //  Add the interesting variables to the SolutionCollector
        all_solutions.Add(c);
        all_solutions.Add(p);
        //  Create the variable kBase * c + p
        IntVar v1 = solver.MakeSum(solver.MakeProd(c, kBase), p).Var();
        //  Add it to the SolutionCollector
        all_solutions.Add(v1);

        //  Decision Builder: hot to scour the search tree
        DecisionBuilder db = solver.MakePhase (letters,
                                               Solver.CHOOSE_FIRST_UNBOUND,
                                               Solver.ASSIGN_MIN_VALUE);
        solver.Solve(db, all_solutions);

        //  Retrieve the solutions
        int numberSolutions = all_solutions.SolutionCount();
        Console.WriteLine ("Number of solutions: " + numberSolutions);

        for (int index = 0; index < numberSolutions; ++index) {
            Assignment solution = all_solutions.Solution(index);
            Console.WriteLine ("Solution found:");
            Console.WriteLine ("v1=" + solution.Value(v1));
        }
    }
开发者ID:RickOne16,项目名称:or-tools,代码行数:61,代码来源:cp_is_fun2.cs

示例4: Solve

  /**
   *
   * Implements the all interval problem.
   * See http://www.hakank.org/google_or_tools/all_interval.py
   *
   */
  private static void Solve(int n=12)
  {
    Solver solver = new Solver("AllInterval");


    //
    // Decision variables
    //
    IntVar[] x =  solver.MakeIntVarArray(n, 0, n-1, "x");
    IntVar[] diffs = solver.MakeIntVarArray(n-1, 1, n-1, "diffs");

    //
    // Constraints
    //
    solver.Add(x.AllDifferent());
    solver.Add(diffs.AllDifferent());

    for(int k = 0; k < n - 1; k++) {
      // solver.Add(diffs[k] == (x[k + 1] - x[k]).Abs());
      solver.Add(diffs[k] == (x[k + 1] - x[k].Abs()));
    }


    // symmetry breaking
    solver.Add(x[0] < x[n - 1]);
    solver.Add(diffs[0] < diffs[1]);


    //
    // Search
    //
    DecisionBuilder db = solver.MakePhase(x,
                                          Solver.CHOOSE_FIRST_UNBOUND,
                                          Solver.ASSIGN_MIN_VALUE);

    solver.NewSearch(db);

    while (solver.NextSolution()) {
      Console.Write("x: ");
      for(int i = 0; i < n; i++) {
          Console.Write("{0} ", x[i].Value());
      }
      Console.Write("  diffs: ");
      for(int i = 0; i < n-1; i++) {
          Console.Write("{0} ", diffs[i].Value());
      }
      Console.WriteLine();
    }

    Console.WriteLine("\nSolutions: {0}", solver.Solutions());
    Console.WriteLine("WallTime: {0}ms", solver.WallTime());
    Console.WriteLine("Failures: {0}", solver.Failures());
    Console.WriteLine("Branches: {0} ", solver.Branches());

    solver.EndSearch();

  }
开发者ID:9thbit,项目名称:csplib,代码行数:63,代码来源:all_interval.cs

示例5: calc

  /**
   * Ensure that the sum of the segments
   * in cc == res
   *
   */
  public static void calc(Solver solver,
                           int[] cc,
                           IntVar[,] x,
                           int res)
  {

    int ccLen = cc.Length;
    if (ccLen == 4) {

      // for two operands there's
      // a lot of possible variants
      IntVar a = x[cc[0]-1, cc[1]-1];
      IntVar b = x[cc[2]-1, cc[3]-1];

      IntVar r1 = a + b == res;
      IntVar r2 = a * b == res;
      IntVar r3 = a * res == b;
      IntVar r4 = b * res == a;
      IntVar r5 = a - b == res;
      IntVar r6 = b - a == res;

      solver.Add(r1+r2+r3+r4+r5+r6 >= 1);

    } else {

      // For length > 2 then res is either the sum
      // the the product of the segment

      // sum the numbers
      int len = cc.Length / 2;
      IntVar[] xx = (from i in Enumerable.Range(0, len)
                     select x[cc[i*2]-1,cc[i*2+1]-1]).ToArray();

      // Sum
      IntVar this_sum = xx.Sum() == res;

      // Product
      // IntVar this_prod = (xx.Prod() == res).Var(); // don't work
      IntVar this_prod;
      if (xx.Length == 3) {
        this_prod = (x[cc[0]-1,cc[1]-1] *
                     x[cc[2]-1,cc[3]-1] *
                     x[cc[4]-1,cc[5]-1]) == res;
      } else {
        this_prod = (
                     x[cc[0]-1,cc[1]-1] *
                     x[cc[2]-1,cc[3]-1] *
                     x[cc[4]-1,cc[5]-1] *
                     x[cc[6]-1,cc[7]-1]) == res;

      }

      solver.Add(this_sum + this_prod >= 1);


    }
  }
开发者ID:HanumathRao,项目名称:hakank,代码行数:62,代码来源:kenken2.cs

示例6: Solve

  /**
   *
   * Scheduling speakers problem
   *
   *  From Rina Dechter, Constraint Processing, page 72
   *  Scheduling of 6 speakers in 6 slots.
   *
   * See http://www.hakank.org/google_or_tools/scheduling_speakers.py
   *
   */
  private static void Solve()
  {
    Solver solver = new Solver("SchedulingSpeakers");


    // number of speakers
    int n = 6;

    // slots available to speak
    int[][] available = {
                    // Reasoning:
      new int[] {3,4,5,6},    // 2) the only one with 6 after speaker F -> 1
      new int[] {3,4},        // 5) 3 or 4
      new int[] {2,3,4,5},    // 3) only with 5 after F -> 1 and A -> 6
      new int[] {2,3,4},      // 4) only with 2 after C -> 5 and F -> 1
      new int[] {3,4},        // 5) 3 or 4
      new int[] {1,2,3,4,5,6} // 1) the only with 1
    };


    //
    // Decision variables
    //
    IntVar[] x =  solver.MakeIntVarArray(n, 1, n, "x");

    //
    // Constraints
    //
    solver.Add(x.AllDifferent());

    for(int i = 0; i < n; i++) {
      solver.Add(x[i].Member(available[i]));
    }


    //
    // Search
    //
    DecisionBuilder db = solver.MakePhase(x,
                                          Solver.CHOOSE_FIRST_UNBOUND,
                                          Solver.ASSIGN_MIN_VALUE);

    solver.NewSearch(db);

    while (solver.NextSolution()) {
      Console.WriteLine(string.Join(",", (from i in x select i.Value())));
    }

    Console.WriteLine("\nSolutions: {0}", solver.Solutions());
    Console.WriteLine("WallTime: {0}ms", solver.WallTime());
    Console.WriteLine("Failures: {0}", solver.Failures());
    Console.WriteLine("Branches: {0} ", solver.Branches());

    solver.EndSearch();

  }
开发者ID:RickOne16,项目名称:or-tools,代码行数:66,代码来源:scheduling_speakers.cs

示例7: Solve

  /**
   *
   * Dudeney numbers
   * From Pierre Schaus blog post
   * Dudeney number
   * http://cp-is-fun.blogspot.com/2010/09/test-python.html
   * """
   * I discovered yesterday Dudeney Numbers
   * A Dudeney Numbers is a positive integer that is a perfect cube such that the sum
   * of its decimal digits is equal to the cube root of the number. There are only six
   * Dudeney Numbers and those are very easy to find with CP.
   * I made my first experience with google cp solver so find these numbers (model below)
   * and must say that I found it very convenient to build CP models in python!
   * When you take a close look at the line:
   *     solver.Add(sum([10**(n-i-1)*x[i] for i in range(n)]) == nb)
   * It is difficult to argue that it is very far from dedicated
   * optimization languages!
   * """
   *
   * Also see: http://en.wikipedia.org/wiki/Dudeney_number
   *
   */
  private static void Solve()
  {

    Solver solver = new Solver("DudeneyNumbers");

    //
    // data
    //
    int n = 6;

    //
    // Decision variables
    //
    IntVar[] x = solver.MakeIntVarArray(n, 0, 9, "x");
    IntVar nb = solver.MakeIntVar(3, (int)Math.Pow(10,n), "nb");
    IntVar s = solver.MakeIntVar(1,9*n+1,"s");

    //
    // Constraints
    //
    solver.Add(nb == s*s*s);
    solver.Add(x.Sum() == s);

    // solver.Add(ToNum(x, nb, 10));

    // alternative
    solver.Add((from i in Enumerable.Range(0, n)
                select (x[i]*(int)Math.Pow(10,n-i-1)).Var()).
               ToArray().Sum() == nb);


    //
    // Search
    //
    DecisionBuilder db = solver.MakePhase(x,
                                          Solver.INT_VAR_DEFAULT,
                                          Solver.INT_VALUE_DEFAULT);


    solver.NewSearch(db);

    while (solver.NextSolution()) {
      Console.WriteLine(nb.Value());
    }

    Console.WriteLine("\nSolutions: {0}", solver.Solutions());
    Console.WriteLine("WallTime: {0}ms", solver.WallTime());
    Console.WriteLine("Failures: {0}", solver.Failures());
    Console.WriteLine("Branches: {0} ", solver.Branches());

    solver.EndSearch();

  }
开发者ID:RickOne16,项目名称:or-tools,代码行数:75,代码来源:dudeney.cs

示例8: Solve

  /**
   *
   * Solve the SEND+MORE=MONEY problem
   *
   */
  private static void Solve()
  {
    Solver solver = new Solver("SendMoreMoney");

    //
    // Decision variables
    //
    IntVar S = solver.MakeIntVar(0, 9, "S");
    IntVar E = solver.MakeIntVar(0, 9, "E");
    IntVar N = solver.MakeIntVar(0, 9, "N");
    IntVar D = solver.MakeIntVar(0, 9, "D");
    IntVar M = solver.MakeIntVar(0, 9, "M");
    IntVar O = solver.MakeIntVar(0, 9, "O");
    IntVar R = solver.MakeIntVar(0, 9, "R");
    IntVar Y = solver.MakeIntVar(0, 9, "Y");

    // for AllDifferent()
    IntVar[] x = new IntVar[] {S,E,N,D,M,O,R,Y};

    //
    // Constraints
    //
    solver.Add(x.AllDifferent());
    solver.Add(S*1000 + E*100 + N*10 + D + M*1000 + O*100 + R*10 + E ==
               M*10000 + O*1000 + N*100 + E*10 + Y);

    solver.Add(S > 0);
    solver.Add(M > 0);

    //
    // Search
    //
    DecisionBuilder db = solver.MakePhase(x,
                                          Solver.CHOOSE_FIRST_UNBOUND,
                                          Solver.ASSIGN_MIN_VALUE);

    solver.NewSearch(db);
    while (solver.NextSolution()) {
      for(int i = 0; i < 8; i++) {
        Console.Write(x[i].ToString() + " ");
      }
      Console.WriteLine();
    }

    Console.WriteLine("\nWallTime: " + solver.WallTime() + "ms ");
    Console.WriteLine("Failures: " + solver.Failures());
    Console.WriteLine("Branches: " + solver.Branches());

    solver.EndSearch();

  }
开发者ID:RickOne16,项目名称:or-tools,代码行数:56,代码来源:send_more_money.cs

示例9: Solve

  /**
   *
   * Magic sequence problem.
   *
   * This is a port of the Python model
   * https://code.google.com/p/or-tools/source/browse/trunk/python/magic_sequence_distribute.py
   * """
   * This models aims at building a sequence of numbers such that the number of
   * occurrences of i in this sequence is equal to the value of the ith number.
   * It uses an aggregated formulation of the count expression called
   * distribute().
   * """
   *
   */
  private static void Solve(int size)
  {

    Solver solver = new Solver("MagicSequence");

    Console.WriteLine("\nSize: {0}", size);

    //
    // data
    //
    int[] all_values = new int[size];
    for (int i = 0; i < size; i++) {
      all_values[i] = i;
    }

    //
    // Decision variables
    //
    IntVar[] all_vars  = solver.MakeIntVarArray(size, 0, size - 1, "vars");

    //
    // Constraints
    //
    solver.Add(all_vars.Distribute(all_values, all_vars));
    solver.Add(all_vars.Sum() == size);


    //
    // Search
    //
    DecisionBuilder db = solver.MakePhase(all_vars,
                                          Solver.CHOOSE_FIRST_UNBOUND,
                                          Solver.ASSIGN_MIN_VALUE);

    solver.NewSearch(db);

    while (solver.NextSolution()) {
      for(int i = 0; i < size; i++) {
        Console.Write(all_vars[i].Value() + " ");
      }
      Console.WriteLine();
    }

    Console.WriteLine("\nSolutions: {0}", solver.Solutions());
    Console.WriteLine("WallTime: {0}ms", solver.WallTime());
    Console.WriteLine("Failures: {0}", solver.Failures());
    Console.WriteLine("Branches: {0} ", solver.Branches());

    solver.EndSearch();

  }
开发者ID:9thbit,项目名称:csplib,代码行数:65,代码来源:magic_sequence.cs

示例10: Solve

  /**
   *
   * Implements toNum: channeling between a number and an array.
   * See http://www.hakank.org/or-tools/toNum.py
   *
   */
  private static void Solve()
  {
    Solver solver = new Solver("ToNum");

    int n = 5;
    int bbase = 10;

    //
    // Decision variables
    //
    IntVar[] x = solver.MakeIntVarArray(n, 0, bbase - 1, "x");
    IntVar num = solver.MakeIntVar(0, (int)Math.Pow(bbase, n) - 1, "num");

    //
    // Constraints
    //

    solver.Add(x.AllDifferent());
    solver.Add(ToNum(x, num, bbase));

    // extra constraint (just for fun)
    // second digit should be 7
    // solver.Add(x[1] == 7);

    //
    // Search
    //
    DecisionBuilder db = solver.MakePhase(x,
                                          Solver.CHOOSE_FIRST_UNBOUND,
                                          Solver.ASSIGN_MIN_VALUE);

    solver.NewSearch(db);

    while (solver.NextSolution()) {
      Console.Write("\n" + num.Value() + ": ");
      for(int i = 0; i < n; i++) {
        Console.Write(x[i].Value() + " ");
      }
    }

    Console.WriteLine("\nSolutions: {0}", solver.Solutions());
    Console.WriteLine("WallTime: {0}ms", solver.WallTime());
    Console.WriteLine("Failures: {0}", solver.Failures());
    Console.WriteLine("Branches: {0} ", solver.Branches());

    solver.EndSearch();

  }
开发者ID:RickOne16,项目名称:or-tools,代码行数:54,代码来源:to_num.cs

示例11: minus

  public static void minus(Solver solver, 
                           IntVar x, 
                           IntVar y, 
                           IntVar z) 
 {
   solver.Add(z == (x - y).Abs());
 }
开发者ID:RickOne16,项目名称:or-tools,代码行数:7,代码来源:olympic.cs

示例12: Solve

  /**
   *
   * Secret Santa problem in Google CP Solver.
   *
   * From Ruby Quiz Secret Santa
   * http://www.rubyquiz.com/quiz2.html
   * """
   * Honoring a long standing tradition started by my wife's dad, my friends
   * all play a Secret Santa game around Christmas time. We draw names and
   * spend a week sneaking that person gifts and clues to our identity. On the
   * last night of the game, we get together, have dinner, share stories, and,
   * most importantly, try to guess who our Secret Santa was. It's a crazily
   * fun way to enjoy each other's company during the holidays.
   *
   * To choose Santas, we use to draw names out of a hat. This system was
   * tedious, prone to many 'Wait, I got myself...' problems. This year, we
   * made a change to the rules that further complicated picking and we knew
   * the hat draw would not stand up to the challenge. Naturally, to solve
   * this problem, I scripted the process. Since that turned out to be more
   * interesting than I had expected, I decided to share.
   *
   * This weeks Ruby Quiz is to implement a Secret Santa selection script.
   * *  Your script will be fed a list of names on STDIN.
   * ...
   * Your script should then choose a Secret Santa for every name in the list.
   * Obviously, a person cannot be their own Secret Santa. In addition, my friends
   * no longer allow people in the same family to be Santas for each other and your
   * script should take this into account.
   * """
   *
   *  Comment: This model skips the file input and mail parts. We
   *        assume that the friends are identified with a number from 1..n,
   *        and the families is identified with a number 1..num_families.
   *
   * Also see http://www.hakank.org/or-tools/secret_santa.py 
   * Also see http://www.hakank.org/or-tools/secret_santa2.cs 
   *
   */
  private static void Solve()
  {

    Solver solver = new Solver("SecretSanta");

    int[] family = {1,1,1,1, 2, 3,3,3,3,3, 4,4};
    int n = family.Length;

    Console.WriteLine("n = {0}", n);

    IEnumerable<int> RANGE = Enumerable.Range(0, n);

    //
    // Decision variables
    //
    IntVar[] x = solver.MakeIntVarArray(n, 0, n-1, "x");


    //
    // Constraints
    //
    solver.Add(x.AllDifferent());

    // Can't be one own"s Secret Santa
    // (i.e. ensure that there are no fix-point in the array.)
    foreach(int i in RANGE) {
      solver.Add(x[i] != i);
    }


    // No Secret Santa to a person in the same family
    foreach(int i in RANGE) {
      solver.Add(solver.MakeIntConst(family[i]) != family.Element(x[i]));
    }

    //
    // Search
    //
    DecisionBuilder db = solver.MakePhase(x,
                                          Solver.INT_VAR_SIMPLE,
                                          Solver.INT_VALUE_SIMPLE);

    solver.NewSearch(db);

    while (solver.NextSolution()) {
      Console.Write("x:  ");
      foreach(int i in RANGE) {
        Console.Write(x[i].Value() + " ");
      }
      Console.WriteLine();
    }

    Console.WriteLine("\nSolutions: {0}", solver.Solutions());
    Console.WriteLine("WallTime: {0}ms", solver.WallTime());
    Console.WriteLine("Failures: {0}", solver.Failures());
    Console.WriteLine("Branches: {0} ", solver.Branches());

    solver.EndSearch();

  }
开发者ID:RickOne16,项目名称:or-tools,代码行数:98,代码来源:secret_santa.cs

示例13: Solve

  /**
   *
   * Grocery problem.
   *
   * From  Christian Schulte, Gert Smolka, Finite Domain
   * http://www.mozart-oz.org/documentation/fdt/
   * Constraint Programming in Oz. A Tutorial. 2001.
   * """
   * A kid goes into a grocery store and buys four items. The cashier
   * charges $7.11, the kid pays and is about to leave when the cashier
   * calls the kid back, and says 'Hold on, I multiplied the four items
   * instead of adding them; I'll try again; Hah, with adding them the
   * price still comes to $7.11'. What were the prices of the four items?
   * """
   *
   */
  private static void Solve()
  {
    Solver solver = new Solver("Grocery");

    int n = 4;
    int c = 711;

    //
    // Decision variables
    //

    IntVar[] item = solver.MakeIntVarArray(n, 0, c / 2, "item");

    //
    // Constraints
    //
    solver.Add(item.Sum() == c);
    // solver.Add(item[0] * item[1] * item[2] * item[3] == c * 100*100*100);
    // solver.Add(item.Prod() == c * 100*100*100);
    solver.Add(MyProd(item, c * 100*100*100));


    // Symmetry breaking
    Decreasing(solver, item);

    //
    // Search
    //
    DecisionBuilder db = solver.MakePhase(item,
                                          Solver.CHOOSE_FIRST_UNBOUND,
                                          Solver.ASSIGN_MIN_VALUE);

    solver.NewSearch(db);
    while (solver.NextSolution()) {
      for(int i = 0; i < n; i++) {
        Console.Write(item[i].Value() + " ");
      }
      Console.WriteLine();
    }

    Console.WriteLine("\nWallTime: " + solver.WallTime() + "ms ");
    Console.WriteLine("Failures: " + solver.Failures());
    Console.WriteLine("Branches: " + solver.Branches());

    solver.EndSearch();

  }
开发者ID:RickOne16,项目名称:or-tools,代码行数:63,代码来源:grocery.cs

示例14: calc

  /**
   * Ensure that the sum of the segments
   * in cc == res
   *
   */
  public static void  calc(Solver solver,
                           int[] cc,
                           IntVar[,] x,
                           int res)
  {

    // ensure that the values are positive
    int len = cc.Length / 2;
    for(int i = 0; i < len; i++) {
      solver.Add(x[cc[i*2]-1,cc[i*2+1]-1] >= 1);
    }

    // sum the numbers
    solver.Add( (from i in Enumerable.Range(0, len)
                 select x[cc[i*2]-1,cc[i*2+1]-1])
                .ToArray().Sum() == res);
  }
开发者ID:RickOne16,项目名称:or-tools,代码行数:22,代码来源:kakuro.cs

示例15: MyMod

  /**
   *
   * A simple propagator for modulo constraint.
   *
   * This implementation is based on the ECLiPSe version
   * mentioned in "A Modulo propagator for ECLiPSE"
   * http://www.hakank.org/constraint_programming_blog/2010/05/a_modulo_propagator_for_eclips.html
   * The ECLiPSe Prolog source code:
   * http://www.hakank.org/eclipse/modulo_propagator.ecl
   *
   */
  public static void MyMod(Solver solver, IntVar x, IntVar y, IntVar r) {

    long lbx = x.Min();
    long ubx = x.Max();
    long ubx_neg = -ubx;
    long lbx_neg = -lbx;
    int min_x = (int)Math.Min(lbx, ubx_neg);
    int max_x = (int)Math.Max(ubx, lbx_neg);

    IntVar d = solver.MakeIntVar(min_x, max_x, "d");

    // r >= 0
    solver.Add(r >= 0);

    // x*r >= 0
    solver.Add( x*r >= 0);

    // -abs(y) < r
    solver.Add(-y.Abs() < r);

    // r < abs(y)
    solver.Add(r < y.Abs());

    // min_x <= d, i.e. d > min_x
    solver.Add(d > min_x);

    // d <= max_x
    solver.Add(d <= max_x);

    // x == y*d+r
    solver.Add(x - (y*d + r) == 0);

  }
开发者ID:RickOne16,项目名称:or-tools,代码行数:44,代码来源:divisible_by_9_through_1.cs


注:本文中的Solver.Add方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。