0

So my problem sounds like this: Given a list of integer numbers, generate the list of permutations with the property that the absolute value of the difference between 2 consecutive values from the permutation is <=3. For example : L=[2,7,5] ==> [[2,5,7], [7,5,2]].

So far I wrote this

domains 
list=integer*
lista=list*

predicates
perm(list,list)
permutations(list,lista,integer)
delete(integer,list,list)
diff(list,integer)

clauses
perm([],[]).
perm(Y,[A|X]):-
     delete(A,Y,Y1),
     perm(Y1,X).
delete(A,[A|X],X).
delete(A,[B|X],[B|Y]):-
     delete(A,X,Y).

perm_aux(L,X,3):-
     perm(L,X),
     diff(X,R),
     abs(R)<=3.

diff([],0).
diff(???):-
  ??????

permutations(L,R,3):-
     findall(X,perm_aux(L,X,3),R).

So I'm stuck in the part where I make the difference. I have no idea how to do it for every 2 consecutive elements. Please help me.

4

1 回答 1

1

我不会diff返回差异,而是给它你想要的最大差异,让它在达到太大差异时立即失败,或者成功。

所以diff(List, Max).并调用它,而不是:

diff(X,R),
abs(R)<=3.  % Note that this should be =<

你会有:

diff(X, 3).

那么你的基本情况是:

diff([], _).   % Empty list always succeeds
diff([_], _).  % Single element list always succeeds

你的递归案例看起来像:

diff([X,Y|T], Max) :-
    abs(X-Y) =< Max,
    diff([Y|T], Max).

如果您想diff提供连续值的最大绝对差,您可以将其定义为:

max_diff(X, Max) :-
    max_diff(X, 0, Max).
max_diff([], M, M).
max_diff([_], M, M).
max_diff([X,Y|T], MaxSoFar, Max) :-
    Diff is abs(X-Y),
    (   Diff > MaxSoFar
    ->  max_diff([Y|T], Diff, Max)
    ;   max_diff([Y|T], MaxSoFar, Max)
    ).
于 2014-01-11T22:10:25.083 回答