Let's say I have list(A,X,Y,R)
and i want to get X
and Y
two values from A
that are different and all the other A
values go to R
.
How could I do this ?
Examples
?- list([],X,Y,R). false.
?- list([1],X,Y,R). false.
?- list([1,2],X,Y,R). X=1, Y=2, R=[];
X=2, Y=1, R=[].
?- list([1,1],X,Y,R). X=1, Y=1, R=[];
X=1, Y=1, R=[].
?- list([1,2,3],X,Y,R). X=1, Y=2, R=[3];
X=1, Y=3, R=[2];
X=2, Y=1, R=[3];
X=2, Y=3, R=[1]; X=3, Y=1, R=[2]; X=3, Y=2, R=[1].
CodePudding user response:
Okey, here you have a general solution. I've tried it in SWI-prolog, but if any predicate doesn't work for you at least you can look for an equivalent:
list([A,B|T], X, Y, T) :-
permutation([A,B], [X, Y]).
list([A,B|T], X, Y, [D|R]) :-
permutation([C, D], [A,B]),
list([C|T], X, Y, R).
Breakdown:
- Base case:
X
andY
are the two first elements in any order.R
would be the tail of the list. - Recursive case: From the first two elements, pick one (
D
) and remove it from the list before trying again, then add it toR
.
It passes the examples you've given, although the solutions aren't retrieved in the same order as you wrote.