1

我正在尝试生成三个列表的组合,如下所示:

A = [[1], [1], [1]] ;
A = [[1], [1], [2]] ;
A = [[1], [1], [3]] ;
A = [[1], [1], [1, 2]] ;
A = [[1], [1], [1, 3]] ;
A = [[1], [1], [2, 3]] ;
A = [[1], [1], [1, 2, 3]] ;
A = [[1], [2], [1]] ;
A = [[1], [2], [2]] ;
...

我想避免排列。例如,如果程序计算[[1], [1], [2]],我不想计算[[1], [2], [1]]

这是我到目前为止所拥有的(它不会避免排列):

% generate a list with 3 combination lists
genera([N1,N2,N3]):- 
tots2(N), num2(M1), combination(M1,N,N1), num2(M2), 
combination(M2,N,N2), num2(M3), combination(M3,N,N3).

num2(N):- member(N, [1,2,3]).
tots2(N):- N = [1,2,3].

% combination(K,L,C) :- C is a list of K distinct elements 
%    chosen from the list L

combination(0,_,[]).
combination(K,L,[X|Xs]) :- K > 0,
   el(X,L,R), K1 is K-1, combination(K1,R,Xs).

% Find out what the following predicate el/3 exactly does.

el(X,[X|L],L).
el(X,[_|L],R) :- el(X,L,R).
4

1 回答 1

1

我不知道我的解决方案是否避免了排序谓词中某处的隐藏排列,但我认为可以按照您想要的方式工作:

generator0(MaxValue, List) :-
    between(1, MaxValue, Len),
    length(List, Len),
    maplist(between(1, MaxValue), List),
    sort(List, List).

generator(List) :-
    length(List, 3),
    maplist(generator0(3), List),
    msort(List, List).

这是来自的示例输出generator/1

?- generator(X).
X = [[1], [1], [1]] ;
X = [[1], [1], [2]] ;
X = [[1], [1], [3]] ;
X = [[1], [1], [1, 2]] ;
X = [[1], [1], [1, 3]] ;
X = [[1], [1], [2, 3]] ;
X = [[1], [1], [1, 2, 3]] ;
X = [[1], [2], [2]] ;
X = [[1], [2], [3]] ;
X = [[1], [2], [2, 3]] ;
X = [[1], [3], [3]] ;
X = [[1], [1, 2], [2]] ;
于 2014-04-25T09:12:18.563 回答