2013-04-14 18 views
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). 

回答

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]] ;