簡體   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