sten
sten

Reputation: 7486

Combinations in all orders

I want to generate all pairs of all the numbers of a range 1..N in all orders i.e. [X,Y] and [Y,X]

I found these here : http://kti.ms.mff.cuni.cz/~bartak/prolog/combinatorics.html

 comb(0,_,[]).
 comb(N,[X|T],[X|Comb]):-N>0,N1 is N-1,comb(N1,T,Comb).
 comb(N,[_|T],Comb):-N>0,comb(N,T,Comb).

 comb_rep(0,_,[]).
 comb_rep(N,[X|T],[X|RComb]):-N>0,N1 is N-1,comb_rep(N1,[X|T],RComb).
 comb_rep(N,[_|T],RComb):-N>0,comb_rep(N,T,RComb).

 ?- findall(E1,comb_rep(2,[1,2,3],E1),C1),findall(E2,comb(2,[3,2,1],E2),C2),append(C1,C2,C),write(C).

 [[1,1],[1,2],[1,3],[2,2],[2,3],[3,3],[3,2],[3,1],[2,1]]

There have to be an easier way ?

Also i would prefer to do it as GENERATOR, rather than a FULLY rendered list (like the ex above)

Upvotes: 2

Views: 69

Answers (1)

TessellatingHeckler
TessellatingHeckler

Reputation: 29033

I suspect I am missing something because this does so much less than the code you posted, but this seems to create the pairs how you ask:

limit_pairs(N, [X, Y]) :-
    between(1, N, X),
    between(1, N, Y).

e.g.

?- limit_pairs(3, P).
P = [1, 1]
P = [1, 2]
P = [1, 3]
P = [2, 1]
P = [2, 2]
P = [2, 3]
P = [3, 1]
P = [3, 2]
P = [3, 3]

Upvotes: 3

Related Questions