Combinations of multiple lists - Prolog

后端 未结 4 1824
闹比i
闹比i 2020-12-11 20:10

I need to find the combinations in a list of lists. For example, give the following list,

List = [[1, 2], [1, 2, 3]]

These should be the ou

4条回答
  •  遥遥无期
    2020-12-11 21:15

    This answer hunts the bounty offered "for a pure solution that also takes into account for Ess". Here we generalize this previous answer like so:

    list_crossproduct(Xs, []) :-
       member([], Xs).
    list_crossproduct(Xs, Ess) :-
       Ess = [E0|_],
       same_length(E0, Xs),
       maplist(maybelonger_than(Ess), Xs),
       list_comb(Xs, Ess).
    
    maybelonger_than(Xs, Ys) :-
       maybeshorter_than(Ys, Xs).
    
    maybeshorter_than([], _).
    maybeshorter_than([_|Xs], [_|Ys]) :-
       maybeshorter_than(Xs, Ys).
    

    list_crossproduct/2 gets bidirectional by relating Xs and Ess early.

    ?- list_comb(Xs, [[1,2,3],[1,2,4],[1,2,5]]).
    nontermination                                % BAD!
    
    ?- list_crossproduct(Xs, [[1,2,3],[1,2,4],[1,2,5]]).
       Xs = [[1],[2],[3,4,5]]      % this now works, too
    ;  false.
    

    Sample query having multiple answers:

    ?- list_crossproduct(Xs, [[1,2,3],[1,2,4],[1,2,5],X,Y,Z]).
       X = [1,2,_A],
       Y = [1,2,_B],
       Z = [1,2,_C], Xs = [[1],[2],[3,4,5,_A,_B,_C]]
    ;  X = [1,_A,3],
       Y = [1,_A,4],
       Z = [1,_A,5], Xs = [[1],[2,_A],[3,4,5]]
    ;  X = [_A,2,3],
       Y = [_A,2,4],
       Z = [_A,2,5], Xs = [[1,_A],[2],[3,4,5]]
    ;  false.
    

提交回复
热议问题