Please help me to solve this problem:
subset(N, [1,2,3], L).
if N=2, I want the result is that:
[1,2];
[2,1];
[1,3];
[3,1];
[2,3];
[3,2];
(in any order)
Please help me to solve this problem:
subset(N, [1,2,3], L).
if N=2, I want the result is that:
[1,2];
[2,1];
[1,3];
[3,1];
[2,3];
[3,2];
(in any order)
I rewrite this solution: (based on: Permuted combinations of the elements of a list - Prolog)
subset(N, InList, Out) :-
splitSet(InList,_,SubList),
permutation(SubList,Out),
length(Out, N).
splitSet([ ],[ ],[ ]).
splitSet([H|T],[H|L],R) :-
splitSet(T,L,R).
splitSet([H|T],L,[H|R]) :-
splitSet(T,L,R).
The result (tested in SWI-Prolog):
?- subset(2,[1,2,3],R).
R = [2, 3] ;
R = [3, 2] ;
R = [1, 3] ;
R = [3, 1] ;
R = [1, 2] ;
R = [2, 1] ;
false.
Well, your base case is trivial:
subset(0,Lst,[]).
If N>0, you have 2 choices as to what to do with the first element of Lst:
You might think you have to worry about Lst being too short (or N being too big: same thing), but if you've coded the above properly, it should be taken care of for you.
Hoep that's enough to get you started.
subset(0, _, []).
subset(N, [X | T], [X | R]) :- N > 0, N1 is N - 1, subset(N1, T, R).
subset(N, [_ | T], R) :- N > 0, subset(N, T, R).
The result is that:
[1,2];[1,3];[2,3]; – Welcome789 Feb 01 '12 at 07:19