k7starter
k7starter

Reputation: 3

Prolog - Split one list into 2 which contain all the members of the original one in any order

I'm not really good with lists in Prolog. What I'm trying to do is to split one list [1,2,3,4] into two lists. The catch is that the elements of those two lists can be in any order.

This is what I have right now:

divideList([],[],[]).
divideList(L1,L2,[H|T]) :-
    select(H,L1,L1C),
    length(L1,Length1),
    length([H|T],LengthHT),
    Length1 =< LengthHT,
    divideList(L1C,L2,T).
divideList(L1,L2,[H|T]) :-
    select(H,L2,L2C),
    length(L2,Length2),
    length([H|T],LengthHT),
    Length2 =< LengthHT,
    divideList(L1,L2C,T).

It works when I put in all the lists and it just has to check if it's true or false.

?- divideList([1,2],[4,3],[1,2,3,4]).
true .
?- divideList([2,1],[4,3],[1,2,3,4]).
true .
?- divideList([2,1],[3,4],[1,2,3,4]).
true .

However if I try to do this: ?- divideList(A,[3,4],[1,2,3,4]).

It shows me this ERROR: Out of global stack .

When I want it to show me this:

?- divideList(A,[3,4],[1,2,3,4]).
A = [1,2] ;
A = [2,1].

Any ideas on how to fix this?

Upvotes: 0

Views: 107

Answers (1)

lurker
lurker

Reputation: 58304

You could simplify it a bit using permutation/2:

divideList([A|As], [B|Bs], L) :-
    permutation(L, P),
    append([A|As], [B|Bs], P).

The [A|As] and [B|Bs] prevent [] from being a solution for the first or second argument.

Upvotes: 1

Related Questions