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


C# IntVar.Sum方法代码示例

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


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

示例1: ToNum

  /**
   *
   *  toNum(solver, a, num, base)
   *
   *  channelling between the array a and the number num.
   *
   */
  private static Constraint ToNum(IntVar[] a, IntVar num, int bbase) {
    int len = a.Length;

    IntVar[] tmp = new IntVar[len];
    for(int i = 0; i < len; i++) {
      tmp[i] = (a[i]*(int)Math.Pow(bbase,(len-i-1))).Var();
    }
     return tmp.Sum() == num;
  }
开发者ID:RickOne16,项目名称:or-tools,代码行数:16,代码来源:to_num.cs

示例2: Solve

  /**
   *
   * Decomposition of alldifferent_except_0
   *
   * See http://www.hakank.org/google_or_tools/map.py
   *
   *
   */
  private static void Solve()
  {
    Solver solver = new Solver("AllDifferentExcept0");

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

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

    //
    // Constraints
    //
    AllDifferentExcept0(solver, x);

    // we also require at least 2 0's
    IntVar[] z_tmp = new IntVar[n];
    for(int i = 0; i < n; i++) {
      z_tmp[i] = x[i] == 0;
    }
    IntVar z = z_tmp.Sum().VarWithName("z");
    solver.Add(z == 2);


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

    solver.NewSearch(db);
    while (solver.NextSolution()) {
      Console.Write("z: {0}  x: ", z.Value());
      for(int i = 0; i < n; i++) {
        Console.Write("{0} ", 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,代码行数:61,代码来源:alldifferent_except_0.cs

示例3: Solve

  /**
   *
   * Solves a set covering problem.
   * See  See http://www.hakank.org/or-tools/set_covering4.py
   *
   */
  private static void Solve(int set_partition)
  {

    Solver solver = new Solver("SetCovering4");

    //
    // data
    //

    // Set partition and set covering problem from
    // Example from the Swedish book
    // Lundgren, Roennqvist, Vaebrand
    // 'Optimeringslaera' (translation: 'Optimization theory'),
    // page 408.
    int num_alternatives = 10;
    int num_objects = 8;

    // costs for the alternatives
    int[] costs = {19, 16, 18, 13, 15, 19, 15, 17, 16, 15};

    // the alternatives, and their objects
    int[,] a = {
      // 1 2 3 4 5 6 7 8    the objects
        {1,0,0,0,0,1,0,0},  // alternative 1
        {0,1,0,0,0,1,0,1},  // alternative 2
        {1,0,0,1,0,0,1,0},  // alternative 3
        {0,1,1,0,1,0,0,0},  // alternative 4
        {0,1,0,0,1,0,0,0},  // alternative 5
        {0,1,1,0,0,0,0,0},  // alternative 6
        {0,1,1,1,0,0,0,0},  // alternative 7
        {0,0,0,1,1,0,0,1},  // alternative 8
        {0,0,1,0,0,1,0,1},  // alternative 9
        {1,0,0,0,0,1,1,0}}; // alternative 10

    //
    // Decision variables
    //
    IntVar[] x = solver.MakeIntVarArray(num_alternatives, 0, 1, "x");
    // number of assigned senators, to be minimized
    IntVar z = x.ScalProd(costs).VarWithName("z");

    //
    // Constraints
    //


    for(int j = 0; j < num_objects; j++) {
      IntVar[] b = new IntVar[num_alternatives];
      for(int i = 0; i < num_alternatives; i++) {
        b[i] = (x[i] * a[i,j]).Var();
      }

      if (set_partition == 1) {
        solver.Add(b.Sum() >= 1);
      } else {
        solver.Add(b.Sum() == 1);
      }
    }


    //
    // objective
    //
    OptimizeVar objective = z.Minimize(1);


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

    solver.NewSearch(db, objective);

    while (solver.NextSolution()) {
      Console.WriteLine("z: " + z.Value());
      Console.Write("Selected alternatives: ");
      for(int i = 0; i < num_alternatives; i++) {
        if (x[i].Value() == 1) {
          Console.Write((i+1) + " ");
        }
      }
      Console.WriteLine("\n");

    }

    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,代码行数:101,代码来源:set_covering4.cs

示例4: Solve

  /**
   *
   * Implements Young tableaux and partitions.
   * See http://www.hakank.org/or-tools/young_tableuax.py
   *
   */
  private static void Solve(int n)
  {
    Solver solver = new Solver("YoungTableaux");

    //
    // data
    //
    Console.WriteLine("n: {0}\n", n);

    //
    // Decision variables
    //
    IntVar[,] x = solver.MakeIntVarMatrix(n, n, 1, n + 1, "x");
    IntVar[] x_flat = x.Flatten();

    // partition structure
    IntVar[] p = solver.MakeIntVarArray(n, 0, n + 1, "p");

    //
    // Constraints
    //
    // 1..n is used exactly once
    for(int i = 1; i <= n; i++) {
      solver.Add(x_flat.Count(i, 1));
    }

    solver.Add(x[0,0] == 1);

    // row wise
    for(int i = 0; i < n; i++) {
      for(int j = 1; j < n; j++) {
        solver.Add(x[i,j] >= x[i,j - 1]);
      }
    }

    // column wise
    for(int j = 0; j < n; j++) {
      for(int i = 1; i < n; i++) {
        solver.Add(x[i,j] >= x[i - 1, j]);
      }
    }

    // calculate the structure (i.e. the partition)
    for(int i = 0; i < n; i++) {
      IntVar[] b = new IntVar[n];
      for(int j = 0; j < n; j++) {
        b[j] = x[i, j] <= n;
      }
      solver.Add(p[i] == b.Sum());
    }

    solver.Add(p.Sum() == n);

    for(int i = 1; i < n; i++) {
      solver.Add(p[i - 1] >= p[i]);
    }



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

    solver.NewSearch(db);

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

      for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
          long val = x[i,j].Value();
          if (val <= n) {
            Console.Write(val + " ");
          }
        }
        if (p[i].Value() > 0) {
          Console.WriteLine();
        }
      }
      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());

//.........这里部分代码省略.........
开发者ID:RickOne16,项目名称:or-tools,代码行数:101,代码来源:young_tableaux.cs

示例5: Solve


//.........这里部分代码省略.........
        {6,2,2,1,1,1},
        {7,3,3,1,1,1},
        {4,1,1,1,1,1},
        {5,1,1,1,1,1},
        {6,1,1,1,1,1},
        {6,2,2,1,1,1}, // ...
        {7,3,3,1,1,1}  // Flight 10
        };

    int num_flights = required_crew.GetLength(0);


    //
    // Decision variables
    //
    IntVar[,] crew = solver.MakeIntVarMatrix(num_flights, num_persons,
                                             0, 1, "crew");
    IntVar[] crew_flat = crew.Flatten();

    // number of working persons
    IntVar num_working = solver.MakeIntVar(1, num_persons, "num_working");

    //
    // Constraints
    //

    // number of working persons
    IntVar[] nw = new IntVar[num_persons];
    for(int p = 0; p < num_persons; p++) {
      IntVar[] tmp = new IntVar[num_flights];
      for(int f = 0; f < num_flights; f++) {
        tmp[f] = crew[f,p];
      }
      nw[p] = tmp.Sum() > 0;
    }
    solver.Add(nw.Sum() == num_working);

    for(int f = 0; f < num_flights; f++) {
      // size of crew
      IntVar[] tmp = new IntVar[num_persons];
      for(int p = 0; p < num_persons; p++) {
        tmp[p] = crew[f,p];
      }
      solver.Add(tmp.Sum() == required_crew[f,0]);

      // attributes and requirements
      for(int a = 0; a < 5; a++) {
        IntVar[] tmp2 = new IntVar[num_persons];
        for(int p = 0; p < num_persons; p++) {
          tmp2[p] = (crew[f,p]*attributes[p,a]).Var();
        }
        solver.Add(tmp2.Sum() >= required_crew[f,a+1]);
      }
    }

    // after a flight, break for at least two flights
    for(int f = 0; f < num_flights - 2; f++) {
      for(int i = 0; i < num_persons; i++) {
        solver.Add(crew[f,i] + crew[f+1,i] + crew[f+2,i] <= 1);
      }
    }

    // extra contraint: all must work at least two of the flights
    /*
    for(int p = 0; p < num_persons; p++) {
      IntVar[] tmp = new IntVar[num_flights];
开发者ID:RickOne16,项目名称:or-tools,代码行数:67,代码来源:crew.cs

示例6: Solve

  /**
   *
   * This is a port of Charles Prud'homme's Java model
   * Partition.java
   * """
   * Partition n numbers into two groups, so that
   * - the sum of the first group equals the sum of the second,
   * - and the sum of the squares of the first group equals the sum of
   *   the squares of the second
   * """
   *
   */
  private static void Solve(int m)
  {

    Solver solver = new Solver("Partition");


    //
    // Decision variables
    //
    IntVar[] x = solver.MakeIntVarArray(m, 1, 2 * m, "x");
    IntVar[] y = solver.MakeIntVarArray(m, 1, 2 * m, "y");


    //
    // Constraints
    //
       // break symmetries
    for (int i = 0; i < m - 1; i++) {
      solver.Add(x[i] < x[i + 1]);
      solver.Add(y[i] < y[i + 1]);
    }
    solver.Add(x[0] < y[0]);

    IntVar[] xy = new IntVar[2 * m];
    for (int i = m - 1; i >= 0; i--) {
      xy[i] = x[i];
      xy[m + i] = y[i];
    }

    solver.Add(xy.AllDifferent());

    int[] coeffs = new int[2 * m];
    for (int i = m - 1; i >= 0; i--) {
      coeffs[i] = 1;
      coeffs[m + i] = -1;
    }
    solver.Add(xy.ScalProd(coeffs) == 0);

    IntVar[] sxy, sx, sy;
    sxy = new IntVar[2 * m];
    sx = new IntVar[m];
    sy = new IntVar[m];
    for (int i = m - 1; i >= 0; i--) {
      sx[i] = x[i].Square().Var();
      sxy[i] = sx[i];
      sy[i] = y[i].Square().Var();
      sxy[m + i] = sy[i];
    }
    solver.Add(sxy.ScalProd(coeffs) == 0);

    solver.Add(x.Sum() == 2 * m * (2 * m + 1) / 4);
    solver.Add(y.Sum() == 2 * m * (2 * m + 1) / 4);
    solver.Add(sx.Sum() == 2 * m * (2 * m + 1) * (4 * m + 1) / 12);
    solver.Add(sy.Sum() == 2 * m * (2 * m + 1) * (4 * m + 1) / 12);

    //
    // Search
    //
    DecisionBuilder db = solver.MakeDefaultPhase(xy);

    SearchMonitor log = solver.MakeSearchLog(10000);
    solver.NewSearch(db, log);

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

    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,代码行数:94,代码来源:partition.cs

示例7: Solve

  /**
   *
   * Solves a set covering problem.
   * See  See http://www.hakank.org/or-tools/set_covering_opl.py
   *
   */
  private static void Solve()
  {

    Solver solver = new Solver("SetCoveringOPL");

    //
    // data
    //
    int num_workers = 32;
    int num_tasks = 15;

    // Which worker is qualified for each task.
    // Note: This is 1-based and will be made 0-base below.
    int[][] qualified =   {
      new int[] { 1,  9, 19,  22,  25,  28,  31 },
      new int[] { 2, 12, 15, 19, 21, 23, 27, 29, 30, 31, 32 },
      new int[] { 3, 10, 19, 24, 26, 30, 32 },
      new int[] { 4, 21, 25, 28, 32 },
      new int[] { 5, 11, 16, 22, 23, 27, 31 },
      new int[] { 6, 20, 24, 26, 30, 32 },
      new int[] { 7, 12, 17, 25, 30, 31 } ,
      new int[] { 8, 17, 20, 22, 23  },
      new int[] { 9, 13, 14,  26, 29, 30, 31 },
      new int[] { 10, 21, 25, 31, 32 },
      new int[] { 14, 15, 18, 23, 24, 27, 30, 32 },
      new int[] { 18, 19, 22, 24, 26, 29, 31 },
      new int[] { 11, 20, 25, 28, 30, 32 },
      new int[] { 16, 19, 23, 31 },
      new int[] { 9, 18, 26, 28, 31, 32 }
    };

    int[] cost = {1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3,
                  3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 8, 9};


    //
    // Decision variables
    //
    IntVar[] hire = solver.MakeIntVarArray(num_workers, 0, 1, "workers");
    IntVar total_cost = hire.ScalProd(cost).Var();

    //
    // Constraints
    //

    for(int j = 0; j < num_tasks; j++) {
      // Sum the cost for hiring the qualified workers
      // (also, make 0-base).
      int len = qualified[j].Length;
      IntVar[] tmp = new IntVar[len];
      for(int c = 0; c < len; c++) {
        tmp[c] = hire[qualified[j][c] - 1];
      }
      solver.Add(tmp.Sum() >= 1);
    }


    //
    // objective
    //
    OptimizeVar objective = total_cost.Minimize(1);


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

    solver.NewSearch(db, objective);

    while (solver.NextSolution()) {
      Console.WriteLine("Cost: " + total_cost.Value());
      Console.Write("Hire: ");
      for(int i = 0; i < num_workers; i++) {
        if (hire[i].Value() == 1) {
          Console.Write(i + " ");
        }
      }
      Console.WriteLine("\n");

    }

    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,代码来源:covering_opl.cs

示例8: Solve

  /**
   *
   * Solves a set covering problem.
   * See  See http://www.hakank.org/or-tools/set_covering3.py
   *
   */
  private static void Solve()
  {

    Solver solver = new Solver("SetCovering3");

    //
    // data
    //

    // Set covering problem from
    // Katta G. Murty: 'Optimization Models for Decision Making',
    // page 302f
    // http://ioe.engin.umich.edu/people/fac/books/murty/opti_model/junior-7.pdf
    int num_groups = 6;
    int num_senators = 10;

    // which group does a senator belong to?
    int[,] belongs = {{1, 1, 1, 1, 1, 0, 0, 0, 0, 0},   // 1 southern
                       {0, 0, 0, 0, 0, 1, 1, 1, 1, 1},   // 2 northern
                       {0, 1, 1, 0, 0, 0, 0, 1, 1, 1},   // 3 liberals
                       {1, 0, 0, 0, 1, 1, 1, 0, 0, 0},   // 4 conservative
                       {0, 0, 1, 1, 1, 1, 1, 0, 1, 0},   // 5 democrats
                       {1, 1, 0, 0, 0, 0, 0, 1, 0, 1}};  // 6 republicans


    //
    // Decision variables
    //
    IntVar[] x = solver.MakeIntVarArray(num_senators, 0, 1, "x");
    // number of assigned senators, to be minimized
    IntVar z = x.Sum().Var();

    //
    // Constraints
    //

    // ensure that each group is covered by at least
    // one senator
    for(int i = 0; i < num_groups; i++) {
      IntVar[] b = new IntVar[num_senators];
      for(int j = 0; j < num_senators; j++) {
        b[j] = (x[j]*belongs[i,j]).Var();
      }
      solver.Add(b.Sum() >= 1);
    }


    //
    // objective
    //
    OptimizeVar objective = z.Minimize(1);


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

    solver.NewSearch(db, objective);

    while (solver.NextSolution()) {
      Console.WriteLine("z: " + z.Value());
      Console.Write("x: ");
      for(int j = 0; j < num_senators; j++) {
        Console.Write(x[j].Value() + " ");
      }
      Console.WriteLine();

      // More details
      for(int j = 0; j < num_senators; j++) {
        if (x[j].Value() == 1) {
          Console.Write("Senator " + (1 + j) +
                           " belongs to these groups: ");
          for(int i = 0; i < num_groups; i++) {
            if (belongs[i,j] == 1) {
              Console.Write((1 + i) + " ");
            }
          }
          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,代码行数:101,代码来源:set_covering3.cs

示例9: Solve

  /**
   *
   * Solves the Seseman convent problem.
   * See http://www.hakank.org/google_or_tools/seseman.py
   *
   */
  private static void Solve(int n = 3)
  {
    Solver solver = new Solver("Seseman");

    //
    // data
    //
    int border_sum = n * n;

    //
    // Decision variables
    //
    IntVar[,] x = solver.MakeIntVarMatrix(n, n, 0, n*n, "x");
    IntVar[] x_flat = x.Flatten();
    IntVar total_sum = x_flat.Sum().Var();


    //
    // Constraints
    //  

    // zero in all middle cells
    for(int i = 1; i < n-1; i++) {
      for(int j = 1; j < n-1; j++) {
        solver.Add(x[i,j] == 0);
      }
    }

    // all borders must be >= 1
    for(int i = 0; i < n; i++) {
      for(int j = 0; j < n; j++) {
        if (i == 0 || j == 0 || i == n - 1 || j == n - 1) {
          solver.Add(x[i,j] >= 1);
        }
      }
    }

    // sum the four borders
    IntVar[] border1 = new IntVar[n];
    IntVar[] border2 = new IntVar[n];
    IntVar[] border3 = new IntVar[n];
    IntVar[] border4 = new IntVar[n];
    for(int i = 0; i < n; i++) {
      border1[i] = x[i,0];
      border2[i] = x[i,n-1];
      border3[i] = x[0,i];
      border4[i] = x[n-1,i];
    }
    solver.Add(border1.Sum() == border_sum);
    solver.Add(border2.Sum() == border_sum);
    solver.Add(border3.Sum() == border_sum);
    solver.Add(border4.Sum() == border_sum);


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

    solver.NewSearch(db);
    while (solver.NextSolution()) {
      Console.WriteLine("total_sum: {0} ", total_sum.Value());
      for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++){ 
          Console.Write("{0} ", x[i,j].Value());
        }
        Console.WriteLine();
      }
      
      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,代码行数:88,代码来源:seseman.cs

示例10: Solve

  /**
   *
   * Ski assignment in Google CP Solver.
   *
   * From   Jeffrey Lee Hellrung, Jr.:
   * PIC 60, Fall 2008 Final Review, December 12, 2008
   * http://www.math.ucla.edu/~jhellrun/course_files/Fall%25202008/PIC%252060%2520-%2520Data%2520Structures%2520and%2520Algorithms/final_review.pdf
   * """
   * 5. Ski Optimization! Your job at Snapple is pleasant but in the winter
   * you've decided to become a ski bum. You've hooked up with the Mount
   * Baldy Ski Resort. They'll let you ski all winter for free in exchange
   * for helping their ski rental shop with an algorithm to assign skis to
   * skiers. Ideally, each skier should obtain a pair of skis whose height
   * matches his or her own height exactly. Unfortunately, this is generally
   * not possible. We define the disparity between a skier and his or her
   * skis to be the absolute value of the difference between the height of
   * the skier and the pair of skis. Our objective is to find an assignment
   * of skis to skiers that minimizes the sum of the disparities.
   * ...
   * Illustrate your algorithm by explicitly filling out the A[i, j] table
   * for the following sample data:
   *  - Ski heights  : 1, 2, 5, 7, 13, 21.
   *  - Skier heights: 3, 4, 7, 11, 18.
   * """
   *
   * Also see http://www.hakank.org/or-tools/ski_assignment.py
   *

   */
  private static void Solve()
  {
    Solver solver = new Solver("SkiAssignment");

    //
    // Data
    //
    int num_skis = 6;
    int num_skiers = 5;
    int[] ski_heights = {1, 2, 5, 7, 13, 21};
    int[] skier_heights = {3, 4, 7, 11, 18};

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


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

    IntVar[] z_tmp = new IntVar[num_skiers];
    for(int i = 0; i < num_skiers; i++) {
      z_tmp[i] = (ski_heights.Element(x[i]) - skier_heights[i]).Abs().Var();
    }

    //    IntVar z = solver.MakeIntVar(0, ski_heights.Sum(), "z");
    //    solver.Add(z_tmp.Sum() == z);
    // The direct cast from IntExpr to IntVar is potentially faster than
    // the above code.
    IntVar z = z_tmp.Sum().VarWithName("z");

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

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

    solver.NewSearch(db, obj);

    while (solver.NextSolution()) {
      Console.Write("z: {0} x: ", z.Value());
      for(int i = 0; i < num_skiers; i++) {
        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,代码行数:93,代码来源:ski_assignment.cs

示例11: Solve

  /**
   *
   * Solves the Magic Square problem.
   * See http://www.hakank.org/or-tools/magic_square.py
   *
   */
  private static void Solve(int n = 4, int num = 0, int print = 1)
  {
    Solver solver = new Solver("MagicSquare");

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

    //
    // Decision variables
    //
    IntVar[,] x = solver.MakeIntVarMatrix(n, n, 1, n*n, "x");
    // for the branching
    IntVar[] x_flat = x.Flatten();

    
    //
    // Constraints
    //
    long s = (n * (n * n + 1)) / 2;
    Console.WriteLine("s: " + s);

    IntVar[] diag1 = new IntVar[n];
    IntVar[] diag2 = new IntVar[n];
    for(int i = 0; i < n; i++) {
      IntVar[] row = new IntVar[n];
      for(int j = 0; j < n; j++) {
        row[j] = x[i,j];
      }
      // sum row to s
      solver.Add(row.Sum() == s);

      diag1[i] = x[i,i];
      diag2[i] = x[i,n - i - 1];
    }

    // sum diagonals to s
    solver.Add(diag1.Sum() == s);
    solver.Add(diag2.Sum() == s);

    // sum columns to s
    for(int j = 0; j < n; j++) {
      IntVar[] col = new IntVar[n];
      for(int i = 0; i < n; i++) {
        col[i] = x[i,j];
      }
      solver.Add(col.Sum() == s);
    }

    // all are different
    solver.Add(x_flat.AllDifferent());

    // symmetry breaking: upper left is 1
    // solver.Add(x[0,0] == 1);


    //
    // Search
    //

    DecisionBuilder db = solver.MakePhase(x_flat,
                                          Solver.CHOOSE_FIRST_UNBOUND,
                                          Solver.ASSIGN_CENTER_VALUE);


    solver.NewSearch(db);

    int c = 0;
    while (solver.NextSolution()) {
      if (print != 0) {
        for(int i = 0; i < n; i++) {
          for(int j = 0; j < n; j++) {
            Console.Write(x[i,j].Value() + " ");
          }
          Console.WriteLine();
        }
        Console.WriteLine();
      }

      c++;
      if (num > 0 && c >= num) {
        break;
      }
    }

    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,代码行数:97,代码来源:magic_square.cs

示例12: Solve


//.........这里部分代码省略.........
    int num_shifts = shifts.Length;
    IntVar[,] day_stat = new IntVar[num_days, num_shifts];
    for(int i = 0; i < num_days; i++) {
      for(int j = 0; j < num_shifts; j++) {
        day_stat[i,j] = solver.MakeIntVar(0, num_nurses, "day_stat");
      }
    }

    //
    // Constraints
    //
    for(int i = 0; i < num_nurses; i++) {
      IntVar[] reg_input = new IntVar[num_days];
      for(int j = 0; j < num_days; j++) {
        reg_input[j] = x[i,j];
      }

      solver.Add(reg_input.Transition(transition_tuples,
                                      initial_state,
                                      accepting_states));
    }

    //
    // Statistics and constraints for each nurse
    //
    for(int nurse = 0; nurse < num_nurses; nurse++) {

      // Number of worked days (either day or night shift)
      IntVar[] nurse_days = new IntVar[num_days];
      for(int day = 0; day < num_days; day++) {
        nurse_days[day] =
            x[nurse, day].IsMember(new int[] { day_shift, night_shift });
      }
      nurse_stat[nurse] = nurse_days.Sum().Var();

      // Each nurse must work between 7 and 10
      // days/nights during this period
      solver.Add(nurse_stat[nurse] >= 7 * week_multiplier / nurse_multiplier);
      solver.Add(nurse_stat[nurse] <= 10 * week_multiplier / nurse_multiplier);

    }

    //
    // Statistics and constraints for each day
    //
    for(int day = 0; day < num_days; day++) {
      IntVar[] nurses = new IntVar[num_nurses];
      for(int nurse = 0; nurse < num_nurses; nurse++) {
        nurses[nurse] = x[nurse, day];
      }
      IntVar[] stats = new IntVar[num_shifts];
      for (int shift = 0; shift < num_shifts; ++shift)
      {
        stats[shift] = day_stat[day, shift];
      }
      solver.Add(nurses.Distribute(stats));

      //
      // Some constraints for each day:
      //
      // Note: We have a strict requirements of
      //       the number of shifts.
      //       Using atleast constraints is harder
      //       in this model.
      //
      if (day % 7 == 5 || day % 7 == 6) {
开发者ID:RickOne16,项目名称:or-tools,代码行数:67,代码来源:nurse_rostering_transition.cs

示例13: scheduling


//.........这里部分代码省略.........
        int v = 1+generator.Next(n); 
        if (n <= printLimit) {
          Console.Write(v);
        }
        tmp.Add(v);
        c++;
      }
      if (n <= printLimit) {
        Console.WriteLine();
      }
      s[i] = tmp.ToArray();
    }

    // the original problem
    /*
    int[][] s = new int[][] {
      new int[] {1,2,3,4},
      new int[] {2,3},
      new int[] {1,4},
      new int[] {1,4}
    };
    */

    Console.WriteLine("\nNumber of generated: {0}", c);

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

    //
    // Decision variables
    //

    // The assignment of persons to a time slot (appointment number 1..n).
    IntVar[] x = solver.MakeIntVarArray(n, 1, n, "x");

    //
    // Constraints
    //

    // Ensure that each person is alotted to exactly one time slot only.
    solver.Add(x.AllDifferent());

    // Ensure that the selected person for the alotted time is avaiable.
    IntVar[] b = new IntVar[n]; 
    foreach(int i in NRange) {
      b[i] = x[i].IsMember(s[i]).Var();
    }
    solver.Add(b.Sum()==n);


    //
    // Search
    //
    DecisionBuilder db = solver.MakePhase(x,
                                          // Solver.INT_VAR_DEFAULT,
                                          // Solver.INT_VAR_SIMPLE,
                                          // Solver.CHOOSE_FIRST_UNBOUND,
                                          // Solver.CHOOSE_RANDOM,
                                          // Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, // <-
                                          Solver.CHOOSE_MIN_SIZE_HIGHEST_MIN,
                                          // Solver.CHOOSE_MIN_SIZE_LOWEST_MAX,
                                          // Solver.CHOOSE_MIN_SIZE_HIGHEST_MAX,
                                          // Solver.CHOOSE_PATH,


                                          Solver.INT_VALUE_DEFAULT
                                          // Solver.INT_VALUE_SIMPLE
                                          // Solver.ASSIGN_MIN_VALUE
                                          // Solver.ASSIGN_MAX_VALUE
                                          // Solver.ASSIGN_RANDOM_VALUE
                                          // Solver.ASSIGN_CENTER_VALUE
                                          );

    solver.NewSearch(db);

    int sols = 0;
    Console.WriteLine("\nSolution:");
    while (solver.NextSolution()) {
      sols++;
      Console.WriteLine("solution #" + sols);
      foreach(int i in NRange) {
        Console.Write(x[i].Value() + " ");
      }

      Console.WriteLine();

      if (sols_to_show > 0 && sols >= sols_to_show) {
        break;
      }

    }

    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());
    // Console.WriteLine("MemoryUsage: {0} ", solver.MemoryUsage());

    solver.EndSearch();

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

示例14: Solve


//.........这里部分代码省略.........
    IntVar[,] day_stat = new IntVar[num_days, num_shifts];
    for(int i = 0; i < num_days; i++) {
      for(int j = 0; j < num_shifts; j++) {
        day_stat[i,j] = solver.MakeIntVar(0, num_nurses, "day_stat");
      }
    }


    //
    // Constraints
    //
    for(int i = 0; i < num_nurses; i++) {
      IntVar[] reg_input = new IntVar[num_days];
      for(int j = 0; j < num_days; j++) {
        reg_input[j] = x[i,j];
      }
      MyRegular(solver, reg_input, n_states, input_max, transition_fn,
                initial_state, accepting_states);



    }

    //
    // Statistics and constraints for each nurse
    //
    for(int i = 0; i < num_nurses; i++) {

      // Number of worked days (either day or night shift)
      IntVar[] b = new IntVar[num_days];
      for(int j = 0; j < num_days; j++) {
        b[j] = ((x[i,j] == day_shift) + (x[i,j] == night_shift)).Var();
      }
      solver.Add(b.Sum() == nurse_stat[i]);

      // Each nurse must work between 7 and 10
      // days/nights during this period
      solver.Add(nurse_stat[i] >= 7);
      solver.Add(nurse_stat[i] <= 10);

    }


    //
    // Statistics and constraints for each day
    //
    for(int j = 0; j < num_days; j++) {
      for(int t = 0; t < num_shifts; t++) {
        IntVar[] b = new IntVar[num_nurses];
        for(int i = 0; i < num_nurses; i++) {
          b[i] = x[i,j] == t;
        }
        solver.Add(b.Sum() == day_stat[j,t]);
      }

      //
      // Some constraints for each day:
      //
      // Note: We have a strict requirements of
      //       the number of shifts.
      //       Using atleast constraints is harder
      //       in this model.
      //
      if (j % 7 == 5 || j % 7 == 6) {
        // special constraints for the weekends
        solver.Add(day_stat[j,day_shift] == 2);
开发者ID:RickOne16,项目名称:or-tools,代码行数:67,代码来源:nurse_rostering_regular.cs

示例15: Solve

  /**
   *
   * Solves the Coins Grid problm.
   * See http://www.hakank.org/google_or_tools/coins_grid.py
   *
   */
  private static void Solve(int n = 31, int c = 14)
  {
    Solver solver = new Solver("CoinsGrid");

    //
    // Decision variables
    //
    IntVar[,] x = solver.MakeIntVarMatrix(n, n, 0, 1 , "x");
    IntVar[] x_flat = x.Flatten();

    //
    // Constraints
    //

    // sum row/columns == c
    for(int i = 0; i < n; i++) {
      IntVar[] row = new IntVar[n];
      IntVar[] col = new IntVar[n];
      for(int j = 0; j < n; j++) {
        row[j] = x[i,j];
        col[j] = x[j,i];
      }
      solver.Add(row.Sum() == c);
      solver.Add(col.Sum() == c);
    }

    // quadratic horizonal distance
    IntVar[] obj_tmp = new IntVar[n * n];
    for(int i = 0; i < n; i++) {
      for(int j = 0; j < n; j++) {
        obj_tmp[i * n + j] = (x[i,j] * (i - j) * (i - j)).Var();
      }
    }
    IntVar obj_var = obj_tmp.Sum().Var();

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

    //
    // Search
    //
    DecisionBuilder db = solver.MakePhase(x_flat,
                                          Solver.CHOOSE_FIRST_UNBOUND,
                                          Solver.ASSIGN_MAX_VALUE);

    solver.NewSearch(db, obj);

    while (solver.NextSolution()) {
      Console.WriteLine("obj: " + obj_var.Value());
      for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
          Console.Write(x[i,j].Value() + " ");
        }
        Console.WriteLine();
      }
      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,代码行数:74,代码来源:coins_grid.cs


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