I’m trying to divide a list in Prolog into 3 equal parts (…well, as equal as possible).
My algorithm is the following:
- Find out the size of the initial list.
- Call the procedure with two extra parameters (the size of the list and a counter that will tell me when I should stop adding elements to one list and start adding to another)
The procedure looks like this:
With 4 parameters:
div3(InitialList,FirstNewList,SecondNewList,ThirdNewList).
With 2 extra parameters:
div3(InitialList,FirstList,SecondList,ThirdList,InitialListSize,Counter).
Here’s my code:
div3([],[],[],[]).
div3([X],[X],[],[]).
div3([X,Y],[X],[Y],[]).
div3([X,Y,Z],[X],[Y],[Z]).
div3([X | Y],A,B,C) :- length([X | Y],Sz),
Sz1 is 0,
div3([X | Y],A,B,C,Sz,Sz1).
div3([X | Y],A,B,C,Sz,Sz1) :- Sz1 < Sz//3, % am I done adding to the 1st list?
append(X,L,A), % add to the 1st list
Sz2 is Sz1+1, % increment the counter
div3(Y,L,B,C,Sz,Sz2),!.
div3([X | Y],A,B,C,Sz,Sz1) :- Sz1 < 2*Sz//3, % am I done adding to the 2nd list?
append(X,L,B), % add to the 2nd list
Sz2 is Sz1+1, % increment the counter
div3(Y,A,L,C,Sz,Sz2),!.
div3([X | Y],A,B,C,Sz,Sz1) :- Sz1 < Sz, % am I done adding to the 3rd list?
append(X,L,C),% add to the 3rd list
Sz2 is Sz1+1, % increment the counter
div3(Y,A,B,L,Sz,Sz2),!.
I think the first part of your code was almost right…
What you are looking for is a recursive predicate with 3 base cases and just one recursive clause.