我想针对以下问题编写Prolog程序: 从集合X = {1 ... 24}确定8个数字y1..y8,使得对于每个n,0 <0。 n&lt;在图24中,有两个数字yi和yj,其中n = yi-yj,yi> YJ。
到目前为止,我尝试了以下内容:
gen(A, B, C, D, E, F, G, H) :-
permutation([A, B, C, D, E, F, G, H, _, _, _,
_, _, _, _, _, _, _, _, _, _, _, _, _],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]).
distance(D, L) :-
random_member(X, L),
random_member(Y, L),
X - Y =:= D.
solution(A, B, C, D, E, F, G, H) :-
gen(A, B, C, D, E, F, G, H),
distance(1, [A, B, C, D, E, F, G, H]),
distance(2, [A, B, C, D, E, F, G, H]),
distance(3, [A, B, C, D, E, F, G, H]),
distance(4, [A, B, C, D, E, F, G, H]),
distance(5, [A, B, C, D, E, F, G, H]),
distance(6, [A, B, C, D, E, F, G, H]),
distance(7, [A, B, C, D, E, F, G, H]),
distance(8, [A, B, C, D, E, F, G, H]),
distance(9, [A, B, C, D, E, F, G, H]),
distance(10, [A, B, C, D, E, F, G, H]),
distance(11, [A, B, C, D, E, F, G, H]),
distance(12, [A, B, C, D, E, F, G, H]),
distance(13, [A, B, C, D, E, F, G, H]),
distance(14, [A, B, C, D, E, F, G, H]),
distance(15, [A, B, C, D, E, F, G, H]),
distance(16, [A, B, C, D, E, F, G, H]),
distance(17, [A, B, C, D, E, F, G, H]),
distance(18, [A, B, C, D, E, F, G, H]),
distance(19, [A, B, C, D, E, F, G, H]),
distance(20, [A, B, C, D, E, F, G, H]),
distance(21, [A, B, C, D, E, F, G, H]),
distance(22, [A, B, C, D, E, F, G, H]),
distance(23, [A, B, C, D, E, F, G, H]),
distance(24, [A, B, C, D, E, F, G, H]).
有人可以帮我吗?
答案 0 :(得分:0)
我更改了您的gen/1
谓词,因为您编写它的方式会产生大量的重复解决方案的回溯。换句话说,它会更快地回溯,并且效率更高。
我还使用了一个列表来表示您的解决方案(编写较少变量的名称)。
最后,我使用了forall/2
而不是写了22次(差不多)同样的事情。
gen([X|Xs],Min,Max,Length) :-
Length>0,
between(Min,Max,X),
Min1 is X+1,
Length1 is Length-1,
gen(Xs,Min1,Max,Length1).
gen([],_,_,0).
gen(X) :- gen(X,1,24,8).
distance(D,L) :-
member(Y1,L),
member(Y2,L),
D =:= Y1 - Y2,
Y1 > Y2.
solution(X) :-
gen(X),
forall(between(2,23,D), once(distance(D,X))).
结果:(用鼠标观察它)
有4个解决方案(我在评论中考虑了更正,因此
1 < N < 24
)
? - 解决方案(X)。
X = [1,2,3,12,16,19,22,24];
X = [1,2,5,11,17,19,22,24];
X = [1,3,6,8,14,20,23,24];
X = [1,3,6,9,13,22,23,24];
假的。