简体   繁体   English

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

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

I'm using the choco solver library to generate a set of puzzles.我正在使用 choco 求解器库来生成一组谜题。 I need to run the solver, check how many solutions there are and if there is more than one, add an extra constraint.我需要运行求解器,检查有多少个解决方案,如果有多个,添加一个额外的约束。 Repeating this will give me a set of constraints (clues) that has a unique solution.重复这将给我一组具有独特解决方案的约束(线索)。

However once I've run model.getSolver(findAllSolutions()) any additional checks return zero solutions.但是,一旦我运行 model.getSolver(findAllSolutions()) 任何其他检查都会返回零解决方案。

I'm guessing I need to somehow reset the model solver but can't find a way of achieving this - I'd rather not generate a new model and recreate the exiting constraints if I have to.我猜我需要以某种方式重置 model 求解器,但找不到实现此目的的方法 - 如果必须,我宁愿不生成新的 model 并重新创建现有约束。

The original code has 110 IntVar's and a huge number of constraints, but I've created a much smaller example.原始代码有 110 个 IntVar 和大量约束,但我创建了一个小得多的示例。

Note: in the real application I use model.getSolver().findAllSolutions(new SolutionCounter(model,2)) to speed things up, but I've omitted that step here.注意:在实际应用中,我使用 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());

For anybody else looking for this, it turns out that the answer is simple.对于其他寻找这个的人来说,答案很简单。

model.getSolver().reset();

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

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