domains
el=integer
list = el*
lista = list*
predicates
aux(list,integer,list)
arrangements(list,integer,lista)
clauses
aux([H|_],1,[H]).
aux([_|L],N,L1):-
aux(L,N,L1).
aux([H|L],N,[H|L1]):-
N<>1,
N1=N-1,
aux(L,N1,L1).
arrangements(L,N,R):-
findall(X,aux(L,N,X),R).
此代码显示列表元素的所有组合。我应该如何修改它以显示安排。我没有想法
安排
[2,3,4] K=2 => [[2,3], [3,2], [2,4], [4,2], [3,4], [4,3]]
组合
[2,3,4] K=2 => [[3,4], [2,3], [2,4]]
答案 0 :(得分:0)
使用select
中的aux/3
获取列表中的任何排列:
aux(L, N, [H|T]) :-
N > 1,
select(H, L, M), % Select an element "H" from "L", leaving "M"
N1 is N-1, % NOTE the "is" here, not "=" !!
aux(M, N1, T). % Recurse with remaining elements "M" and count-1
aux(L, 1, [X]) :- member(X, L).
arrangements(L, N, R):-
findall(X, aux(L, N, X), R).
导致:
| ?- arrangements([2,3,4], 2, R).
R = [[2,3],[2,4],[3,2],[3,4],[4,2],[4,3]]
yes