多个列表的组合 - Prolog [英] Combinations of multiple lists - Prolog
问题描述
我需要在列表列表中找到组合.例如,给出以下列表,
列表 = [[1, 2], [1, 2, 3]]
这些应该是输出,
梳 = [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3]]
另一个例子:
列表 = [[1,2],[1,2],[1,2,3]]梳 = [[1,1,1],[1,1,2],[1,1,3],[1,2,1],[1,2,2],[1,2,3]....等等]
我知道如何为具有两个子列表的列表执行此操作,但它需要适用于任意数量的子列表.
我是 Prolog 新手,请帮忙.
这个答案寻找提供的赏金一个纯粹的解决方案,也考虑到 Ess
".这里我们概括这个前面的像这样回答:
list_crossproduct(Xs, []) :-成员([],Xs).list_crossproduct(Xs, Ess) :-Ess = [E0|_],相同长度(E0,Xs),地图列表(maybelonger_than(Ess),Xs),list_comb(Xs, Ess).可能比(Xs,Ys)更长:-可能比(Ys,Xs)更短.也许比([],_)更短.可能比([_|Xs],[_|Ys])更短:-可能比(Xs,Ys)更短.
list_crossproduct/2
通过提前关联 Xs
和 Ess
获得双向.
有多个答案的示例查询:
?- 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]];错误的.
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.
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.
这篇关于多个列表的组合 - Prolog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!