获取序言中的所有列表集 [英] Get all sets of list in prolog
问题描述
如何生成具有当前长度的列表元素的所有可能集合?
How can I generate all the possible sets of the elements of a list with current length?
?- get_set(X, [1,2,3]).
X = [1,1,1] ;
X = [1,1,2] ;
X = [1,1,3] ;
X = [1,2,1] ;
X = [1,2,2] ;
X = [1,2,3] ;
X = [1,3,1] ;
X = [1,3,2] ;
X = [1,3,3] ;
.....
X = [3,3,2] ;
X = [3,3,3].
UPD:Sharky 给出了很好的答案.但也许这不是最好的.这是另一个:
UPD: there is good answer given by Sharky. But maybe it's not the best. Here is another:
get_set(X,L) :- get_set(X,L,L).
get_set([],[],_).
get_set([X|Xs],[_|T],L) :- member(X,L), get_set(Xs,T,L).
推荐答案
考虑:
get_set(L0, L) :-
length(L, Len),
length(L0, Len),
apply_elem(L0, L).
apply_elem([], _).
apply_elem([X|Xs], L) :-
member(X, L),
apply_elem(Xs, L).
说明:
将输入列表L
的长度确定为Len
允许我们通过 生成唯一变量列表
.然后,我们简单地通过 L0
长度/2member/2
将 L
的元素应用到 L0
的所有成员,如果它们存在(即,如果列表 L
的长度 > 1).根据需要,Prolog 将回溯以将 L
元素的所有可能组合生成到列表 L0
中.
Determining the length of the input list L
as Len
allows us to generate a list of unique variables, L0
, via length/2
. Then, we simply apply elements of L
to all members of L0
via member/2
, which leaves choicepoints for options, should they exist (i.e., if the list L
is of length > 1). Prolog will backtrack to generate all possible combinations of elements of L
into the list L0
, as required.
这篇关于获取序言中的所有列表集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!