gpt4 book ai didi

c# - Microsoft Solver Foundation Services 声明性语法

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:05 24 4
gpt4 key购买 nike

我有以下简单问题,我想用它来试验 [MS Solver Foundation][1]:

我有 10 个槽需要用 1 到 5 范围内的整数填充。我只想强制执行两个约束:

  • 插槽[n] != 插槽[n + 1]
  • 所有插槽的总和应大于20

我可以简单地做出以下决定:

Decision s1 = new Decision(Domain.IntegerRange(1, 5), "slot1");
Decision s2 = new Decision(Domain.IntegerRange(1, 5), "slot2");
Decision s3 = new Decision(Domain.IntegerRange(1, 5), "slot3");
Decision s4 = new Decision(Domain.IntegerRange(1, 5), "slot4");
Decision s5 = new Decision(Domain.IntegerRange(1, 5), "slot5");
Decision s6 = new Decision(Domain.IntegerRange(1, 5), "slot6");
Decision s7 = new Decision(Domain.IntegerRange(1, 5), "slot7");
Decision s8 = new Decision(Domain.IntegerRange(1, 5), "slot8");
Decision s9 = new Decision(Domain.IntegerRange(1, 5), "slot9");
Decision s10 = new Decision(Domain.IntegerRange(1, 5), "slot10");

然后手动设置约束

model.AddConstraints("neighbors not equal",
s1 != s2, s2 != s3, s3 != s4, s4 != s5,
s5 != s6, s6 != s7, s7!= s8, s8 != s9, s9 != s10
);

model.AddConstraint("sum",
s1 + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10 > 20 );

但是,我必须想象有一种更好的方法来做到这一点——希望采用更类似于声明性语法的方法。

最佳答案

代码。

SolverContext context = SolverContext.GetContext();
Model model = context.CreateModel();

Decision[] slot = new Decision[10];

for (int i = 0; i < slot.Length; i++)
{
slot[i] = new Decision(Domain.IntegerRange(1, 5), "slot" + i.ToString());
model.AddDecision(slot[i]);
if (i > 0) model.AddConstraint("neighbors not equal", slot[i-1] != slot[i]);
}

model.AddConstraint("sum", Model.Sum(slot) > 20);

Solution solution = context.Solve();

关于c# - Microsoft Solver Foundation Services 声明性语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1400916/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com