【发布时间】:2015-05-29 20:46:54
【问题描述】:
我正在尝试创建一个函数,该函数能够遍历行向量并输出 n 选择 k 无需递归的可能组合。
例如:3 在 [a,b,c] 上选择 2 输出 [a,b; a, c; b,c]
我发现了这个:How to loop through all the combinations of e.g. 48 choose 5,它展示了如何为固定的 n 选择 k 做这件事,而这个:https://codereview.stackexchange.com/questions/7001/generating-all-combinations-of-an-array 展示了如何获得所有可能的组合。使用后面的代码,我设法在 matlab 中创建了一个非常简单且效率低下的函数,该函数返回了结果:
function [ combi ] = NCK(x,k)
%x - row vector of inputs
%k - number of elements in the combinations
combi = [];
letLen = 2^length(x);
for i = 0:letLen-1
temp=[0];
a=1;
for j=0:length(x)-1
if (bitand(i,2^j))
temp(k) = x(j+1);
a=a+1;
end
end
if (nnz(temp) == k)
combi=[combi; derp];
end
end
combi = sortrows(combi);
end
这适用于非常小的向量,但我需要它能够处理长度至少为 50 的向量。我找到了很多如何递归执行此操作的示例,但是有没有一种有效的方法可以在不递归的情况下执行此操作并且仍然能够执行可变大小的向量和 ks?
【问题讨论】:
-
是作业还是论文?
-
为什么不只是
nchoosek('abc',2)? -
程序员分享了多种语言组合的算法,have an idea (rosetta code, inspired from rosetta stone)
-
这是我正在做的一个模拟。我不能使用 nchoosek,因为 simulink 无法将其导出到 C 代码中。
标签: algorithm matlab combinations