prolog写langford序列错误:toplevel:未定义的程序:langford / 1

时间:2014-12-06 11:43:53

标签: prolog

我正在尝试编写langford序列。 像这样:

73 ?- langford4(L).
L = [4, 1, 3, 1, 2, 4, 3, 2] ;
L = [2, 3, 4, 2, 1, 3, 1, 4] ;

这就是我所做的:

prefix([H|T],L):-cat([H|T],_,L).
sublist(S,L):-prefix(P,L), posfix(S,P).
posfix([H|T],L):-cat(_,[H|T],L).

langford42(L):-
   L = [_,_,_,_,_,_,_,_],
   sublist([1,_,1], L),
   sublist([2,_,_,2], L),
   sublist([3,_,_,_,3], L),
   sublist([4,_,_,_,_,4], L).

或者这个:

langford(L):-
   [X,_,_,_,_,X,_,_],
   [_,Y,_,Y,_,_,_,_],
   [_,_,Z,_,_,_,Z,_],
   [_,_,_,_,P,_,_,P].

感谢。

1 个答案:

答案 0 :(得分:0)

没有得到你的问题,你的代码看起来很好,但无论如何问题,一般来说,很好:我尝试用CLP(FD)和更简单的库内置来解决

% two copies of each number k are k units apart

% constraint solution: would be nice to know how we could speedup this one...    
langford_c(N, S) :-
    M is N*2,
    length(S, M),
    S ins 1..N,
    distances(S, S),
    findall(I-2, between(1,N,I), Cs),
    global_cardinality(S, Cs),
    label(S).

distances([N|T], S) :-
    element(I, S, N),
    element(J, S, N),
    J #= I + N + 1,
    distances(T, S).
distances([], _).

% simple nth1/3 based solution
langford_n(N, S) :-
    M is N*2,
    length(S, M),
    distances(S, 1, N).

distances(S, P, C) :-
    P =< C, !,
    nth1(I, S, P),
    nth1(J, S, P),
    J is I + P + 1,
    Q is P + 1,
    distances(S, Q, C).
distances(_, _, _).

带有这些结果

?- time(langford_n(4, S)).
% 1,102 inferences, 0.000 CPU in 0.000 seconds (98% CPU, 2598909 Lips)
S = [4, 1, 3, 1, 2, 4, 3, 2] ;
% 1,404 inferences, 0.001 CPU in 0.001 seconds (99% CPU, 2679103 Lips)
S = [2, 3, 4, 2, 1, 3, 1, 4] ;
% 1,234 inferences, 0.001 CPU in 0.001 seconds (54% CPU, 2064308 Lips)
false.

?- time(langford_c(4, S)).
% 1,302,863 inferences, 0.489 CPU in 0.491 seconds (100% CPU, 2664067 Lips)
S = [2, 3, 4, 2, 1, 3, 1, 4] ;
% 958,979 inferences, 0.367 CPU in 0.371 seconds (99% CPU, 2611630 Lips)
S = [4, 1, 3, 1, 2, 4, 3, 2] ;
% 359,396 inferences, 0.137 CPU in 0.141 seconds (98% CPU, 2614215 Lips)
false.