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).
This code shows all the combinations of elements of a list. How should I modify it to show the arrangements. I have no ideas
arrangements
[2,3,4] K=2 => [[2,3], [3,2], [2,4], [4,2], [3,4], [4,3]]
combinations
[2,3,4] K=2 => [[3,4], [2,3], [2,4]]
Use select
in aux/3
to get any of the permutations from the list:
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).
Resulting in:
| ?- arrangements([2,3,4], 2, R).
R = [[2,3],[2,4],[3,2],[3,4],[4,2],[4,3]]
yes
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.