Search code examples
prologswi-prolog

Find all subsequences of a list that cover the whole list in prolog


I have a prolog assignmment that I am not able to solve correctly.

The goal is to find all possible subsequences of a given list that together cover the whole list. For example for a list: [a,b,a,b,c,c,c]

The results would be:

    [a,b,a,b,c,c,c]
    [a] + [b] + [a] + [b] + [c] + [c] + [c]
    [a, b] + [a] + [b] + [c, c] + [c]
    [a] + [b] + [a, b] + [c, c] + [c]
    [a] + [b] + [a] + [b] + [c] + [c, c]

... etc.

Could anyone help me with this?

This is my code so far:

    allSubsequences([X|Xs], [[X]|Y]):-
        allSubsequences(Xs, Y).
    allSubsequences([X|Xs], [Y|[Z]]):-
        all_splits([X|Xs], Y, Z),
        Z \= [].

    all_splits([], [], []).
    all_splits([X|Xs], [X], Xs).
    all_splits([X|Xs], [X|Ys], Zs) :- 
        all_splits(Xs, Ys, Zs).

It produces some subsequences but not all of them. Im very new to prolog.


Solution

  • At the end it is just traveling the list and deciding whether to cut or not...

    split([], []).
    split([H|T], [[H|O1]|O2]) :- split(T, O1, O2).
    
    split([H|T], [H|O1], O2) :- split(T, O1, O2).
    split(H, [], O) :- split(H, O).