1
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SolverFoundation.Services;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            var context= SolverContext.GetContext();
            var model = context.CreateModel();

            var index = new Set(Domain.IntegerRange(0, 6), "index");

            var x = new Decision(Domain.IntegerRange(0, 5), "x", index);
            model.AddDecision(x);

            // When I uncomment the following line, values ends
            // up with only 3 elements instead of 7 as expected

            // model.AddConstraint("constraint", x[0] + x[1] + x[2] == 2);

            model.AddGoal("objective", GoalKind.Minimize, Model.Sum(Model.ForEach(index, i => Model.Power(x[i] - 2, 2))));

            context.Solve();
            var values = x.GetValues().ToArray();
        }
    }
}

如果我按原样运行此代码,Solver Foundation 会正确计算七个值,每个值都等于 2。

当我取消注释model.AddConstraint("constraint", x[0] + x[1] + x[2] == 2)时,最后的值只包含三个值:0、1 和 1。为什么它不包含其余值?

这是怎么回事?

4

1 回答 1

1

当我使用主动约束运行您的示例时,它会0+1+1作为解决方案出现并省略x[3] .. x[6]。这看起来像一个错误。他们都应该有价值2

添加以下行以显示结果:

foreach (object[] value in values)
   {
       Console.WriteLine("x[{0}] = {1}", value[1], value[0]);
   }

也许,Nathan Brixius的博客可能会提供一些见解。

添加以下虚拟约束后,我再次获得了完整的变量集:

    model.AddConstraint("constraint2", (x[3] + x[4] + x[5] + x[6]) < 999);

作为替代方案,您可以转向MiniZinc并使用如下简单模型:

set of int: ix = 0..6;
array[ix] of var 0..5: x;

constraint
    x[0] + x[1] + x[2] == 2;

solve minimize sum(i in ix)((x[i] - 2)*(x[i] - 2));

output 
["\nx[" ++ show(i) ++ "] = " ++ show(x[i]) | i in ix] ;
于 2014-02-23T00:42:19.243 回答