Combinatios in List of LIsts Prolog

筅森魡賤 提交于 2020-01-15 04:00:12

问题


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 output,

Comb = [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3]]

Another example:

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

Comb = [[1,1,1],[1,1,2],[1,1,3],[1,2,1],[1,2,2],[1,2,3]....etc]

I know how to do it for a list with two sublists but it needs to work for any number of sublists.

I'm new to prolog, please help.


回答1:


try([],[]).
try([L|Ls],[M|Ms]):-
    member(M,L),
    try(Ls,Ms).

all(L,All) :- findall(M, try(L,M), All).    

try returns one list composed of elements of the sublists of the first argument. all finds all such lists.




回答2:


Here is your answer, cut and dry, as a fellow new prolog programmer myself.

%elementInList(input list, output answer)
answer(ListOfList, AnswerInList) :-
    findall(Ans, combList(ListOfList, Ans), AnswerInList).

%combList(ListOfList, Comb) :-
combList([], []).

combList([Head|Tail], Comb) :-
    combList(Tail, [Element|Tempcomb]),
    elementInList(Head, Element).

%elementInList(List, Element)
elementInList([Head|_], Head).

elementInList([Head|Tail], Element) :-
    elementInList(Tail, Element).

Using the definition answer(InputList, OutputResult), where e.g.

answer([[1,2],[7,8]],Comb).
Comb = [[1, 7], [2, 7], [1, 8], [2, 8]].

and e.g.

answer([[1,2],[2,8],[3,6,9]],Comb).
Comb = [[1, 2, 3], [2, 2, 3], [1, 8, 3], [2, 8, 3], [1, 2, 6], [2, 2, 6], [1, 8|...], [2|...], [...|...]|...].

and so on [X,Y,Z,..] for any number of sublists. You're welcome.



来源:https://stackoverflow.com/questions/10239662/combinatios-in-list-of-lists-prolog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!