Reputation: 126
I copied this code from this page:
% combination(K,L,C) :- C is a list of K distinct elements
% chosen from the list L
combination(0,_,[]).
combination(K,L,[X|Xs]) :- K > 0,
el(X,L,R), K1 is K-1, combination(K1,R,Xs).
el(X,[X|L],L).
el(X,[_|L],R) :- el(X,L,R).
For example, if you enter combination(2,[1,2,3,4],L), the result is:
L = [1, 2] ;
L = [1, 3] ;
L = [1, 4] ;
L = [2, 3] ;
L = [2, 4] ;
L = [3, 4] ;
Now I would like to enter something that allows you to start at a determined point of the combination. For example, something like: combination(2,[1,2,3,4],[1,4],L), and the result:
L = [1, 4] ;
L = [2, 3] ;
L = [2, 4] ;
L = [3, 4] ;
Starting the combination at [1,4] and skipping the "steps" [1,2] and [1,3].
Thanks for you help!
Upvotes: 0
Views: 138
Reputation: 397
try this
combination(0,_,[]).
combination(K,L,[X|Xs]) :-
K > 0,
el(X,L,R),
K1 is K-1,
combination(K1,R,Xs).
generate(K, L, X, Pivot, Resault) :-
bagof(X, L^combination(K, L, X), Bag),
iterate(Bag, Pivot, Resault).
iterate([], _, []).
iterate([P|T], P, [P|T]):-!.
iterate([H|T], P, Res) :-
iterate(T, P, Res).
el(X,[X|L],L).
el(X,[_|L],R) :- el(X,L,R).
use generate/5
like this:
| ?- generate(2, [1,2,3,4], X, [1,4], Res).
Res = [[1,4],[2,3],[2,4],[3,4]]
yes.
first I gather all the solutions in a bag, then I iterate through the bag to find a pivot member, if I find it the resault is a list with the pivot as head, and rest of solutions as tail. and if I don't the resault is an empty list.
not a very wise solution, but works.
Upvotes: 1