1
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]]
lurker
  • 56,987
  • 9
  • 69
  • 103
user3043278
  • 174
  • 1
  • 3
  • 15
  • You're saying it "shows all the combinations of elements" but want to "show the arrangements". Can you clarify with an example? – lurker Jan 11 '14 at 15:40
  • I have provided an example in the question – user3043278 Jan 11 '14 at 15:54
  • 1
    Ah, you want permutations of 3 things taken 2 at a time. :) If you do a google search on "prolog permutations" you'll find a bunch of good information. It can be done very easily using the `select/3` predicate. – lurker Jan 11 '14 at 16:05

1 Answers1

0

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
lurker
  • 56,987
  • 9
  • 69
  • 103