找到所有解决方案后,如何为解决方案评分并选择一个

时间:2017-10-01 10:48:00

标签: prolog

以下是问题,setof返回一组解决方案

solve([A1, A2, A3, B1, B3, C1, C2, C3, T]):-

    permutation([1,2,3,4,5,6,7,8], [A1, A2, A3, B1, B3, C1, C2, C3]),

    T is A1 + A2 + A3,

    A1 + A2 + A3 =:= A1 + B1 + C1,
    A1 + A2 + A3 =:= A3 + B3 + C3,
    A1 + A2 + A3 =:= C1 + C2 + C3.

然后我找到所有解决方案

?- setof(Z,solve([A1,A2,A3,B1,B3,C1,C2,C3,T]),Set).
A1 = 1,
A2 = 4,
A3 = 8,
B1 = 7,
B3 = 3,
C1 = 5,
C2 = 6,
C3 = 2,
T = 13,
Set = [_G5594] ;
A1 = 1,
A2 = 5,
A3 = 6,
B1 = 8,
B3 = 4,
C1 = 3,
C2 = 7,
C3 = 2,
T = 12,
Set = [_G5578]
...

如何过滤和评分结果以找到解决方案的最大值(15)?

1 个答案:

答案 0 :(得分:2)

我建议对此类组合任务使用 CLP(FD)约束

例如:

:- use_module(library(clpfd)).

solution([A1,A2,A3,B1,B3,C1,C2,C3], T):-
        [A1,A2,A3,B1,B3,C1,C2,C3] ins 1..8,
        T #= A1 + A2 + A3,
        A1 + A2 + A3 #= A1 + B1 + C1,
        A1 + A2 + A3 #= A3 + B3 + C3,
        A1 + A2 + A3 #= C1 + C2 + C3.

Prolog系统之间的确切细节略有不同,因此请查看系统手册以获取更多信息。最高可以通过标签选项获得,例如:

?- solution(Vs, T), labeling([max(T)], Vs).
Vs = [8, 8, 8, 8, 8, 8, 8, 8],
T = 24 ;
Vs = [7, 8, 8, 8, 7, 8, 7, 8],
T = 23 ;
Vs = [7, 8, 8, 8, 8, 8, 8, 7],
T = 23 ;
etc.

有关详细信息,请参阅

您可以使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class='list'> <li class='item'> <h1 class='title'></h1> <p class='paragraph'></p> </li> <ul> <label>title</label> <input id='title' type='text' required> <label>Paragraph</label> <input id='par' type='text' required> <input id='submit' type='submit' > 提交到第一个解决方案。