这是一个简单的函数,它将对
k1和
n-k0 进行排列并返回的下一个组合
nchoosek。它完全独立于
n和
k的值,直接从输入数组中获取值。
function [nextc] = nextComb(oldc) nextc = []; o = find(oldc, 1); %// find the first one z = find(~oldc(o+1:end), 1) + o; %// find the first zero *after* the first one if length(z) > 0 nextc = oldc; nextc(1:z-1) = 0; nextc(z) = 1; %// make the first zero a one nextc(1:nnz(oldc(1:z-2))) = 1; %// move previous ones to the beginning else nextc = zeros(size(oldc)); nextc(1:nnz(oldc)) = 1; %// start over endend
(请注意,
else只有在您希望组合从最后一个组合绕到第一个组合时,该子句才是必需的。)
如果使用以下方式调用此函数:
A = [1 1 1 1 1 0 1 0 0 1 1]nextCombination = nextComb(A)
输出将是:
A = 1 1 1 1 1 0 1 0 0 1 1nextCombination = 1 1 1 1 0 1 1 0 0 1 1
然后,您可以将其用作字母(或想要组合的任何元素)的蒙版。
C = ['a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k']C(find(nextCombination))ans = abcdegjk
此顺序中的第一个组合是
1 1 1 1 1 1 1 1 0 0 0
最后是
0 0 0 1 1 1 1 1 1 1 1
要以编程方式生成第一个组合,
n = 11; k = 8;nextCombination = zeros(1,n);nextCombination(1:k) = 1;
现在,您可以遍历组合(或者您愿意等待的数目):
for c = 2:nchoosek(n,k) %// start from 2; we already have 1 nextCombination = nextComb(A); %// do something with the combination...end
对于上面的示例:
nextCombination = [1 1 0];C(find(nextCombination))for c = 2:nchoosek(3,2) nextCombination = nextComb(nextCombination); C(find(nextCombination))endans = abans = acans = bc
注意:
我已经更新了代码;我忘了包括将所有在交换的数字之前出现的1移到数组开头的行。当前代码(除了上面已更正的代码)在此处为ideone
。输出为
4 choose 2:
allCombs = 1 2 1 3 2 3 1 4 2 4 3 4



