繁体   English   中英

重用choco求解器model进一步约束解

[英]Reusing choco solver model to further constrain the solution

我正在使用 choco 求解器库来生成一组谜题。 我需要运行求解器,检查有多少个解决方案,如果有多个,添加一个额外的约束。 重复这将给我一组具有独特解决方案的约束(线索)。

但是,一旦我运行 model.getSolver(findAllSolutions()) 任何其他检查都会返回零解决方案。

我猜我需要以某种方式重置 model 求解器,但找不到实现此目的的方法 - 如果必须,我宁愿不生成新的 model 并重新创建现有约束。

原始代码有 110 个 IntVar 和大量约束,但我创建了一个小得多的示例。

注意:在实际应用中,我使用 model.getSolver().findAllSolutions(new SolutionCounter(model,2)) 来加快速度,但我在这里省略了这一步。

Model model = new Model();
// setup two doors A and B, one has the value 0 the other 1
IntVar doorA = model.intVar("Door A", 0, 1);
IntVar doorB = model.intVar("Door B", 0, 1);
model.allDifferent(new IntVar[]{doorA, doorB}).post();
// setup two windows A and B, one has the value 0 the other 1
IntVar windowA = model.intVar("Window A", 0, 1);
IntVar windowB = model.intVar("Window B", 0, 1);
model.allDifferent(new IntVar[]{windowA, windowB}).post();
// assign the first constraint and count the solutions
model.arithm(doorA,"=",0).post();
// this should force door B to be 1 - there are two remaining solutions
List<Solution> solutions = model.getSolver().findAllSolutions();
System.out.println("results after first clue");
for (Solution s : solutions) {
     System.out.println(">"+s.toString());
}
assertEquals("First clue leaves two solutions",2,solutions.size());
// add second clue
model.arithm(windowA,"=",1).post();
// this should force window B to by 0 - only one valid solution
List<Solution> solutions2 = model.getSolver().findAllSolutions();
System.out.println("results after second clue");
for (Solution s : solutions2) {
   System.out.println(">"+s.toString());
}
assertEquals("Second clue leaves one solution",1,solutions2.size());

对于其他寻找这个的人来说,答案很简单。

model.getSolver().reset();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM