多个列表的组合-Prolog [英] Combinations of multiple lists - Prolog

查看:62
本文介绍了多个列表的组合-Prolog的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在列表列表中找到组合.例如,给出以下列表,

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

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

这些应该是输出,

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

另一个例子:

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.

我是Prolog的新手,请帮助.

I'm new to Prolog, please help.

推荐答案

此答案追捕了提供的"纯解决方案,其中也考虑了Ess "的赏金. 在这里,我们概括了此上一个 像这样回答:

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通过尽早关联XsEss来实现双向.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆