如何找到所有可能的球组合?
How to find all possible combinations of balls?
我需要找到所有可能的方法来从 n
种类型的球中组合 k
数量的球。
假设有 3 种类型的球,我想取 2 种,我想要的结果是:
1 1
1 2
1 3
2 2
2 3
3 3
我正在尝试使用以下行:
unique(nchoosek(repmat(1:n, 1, n), k), 'rows')
我得到:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
如何找到所有有重复但没有相同数字重复的组合?
有 n 种球,取 k,你有 nk 组合,在 MATLAB 中计算为 count = n^k
.
您可以使用 ndgrid
列出这些组合:
n = 3;
k = 2;
l = repmat({1:n},k,1); % k repetitions of the n balls
[l{:}] = ndgrid(l{:}); % find all combinations
l = cellfun(@(e)e(:),l,'uniformoutput',false); % make each l{i} a vector
l = [l{:}]; % turn into a single vector
现在您可以验证 size(l,1) == n^k
。
与 OP 中使用 nchoosek
和 repmat
的代码相比,此代码的优势在于不会生成重复组合,因此此代码应使用较大的 [=17= 值] 和 n
比 OP 中的代码。
对问题的编辑表明不应单独计算同一子集的排列。您可以按如下方式过滤列表 l
以删除同一组球的排列:
l = unique(sort(l,2),'rows');
我需要找到所有可能的方法来从 n
种类型的球中组合 k
数量的球。
假设有 3 种类型的球,我想取 2 种,我想要的结果是:
1 1
1 2
1 3
2 2
2 3
3 3
我正在尝试使用以下行:
unique(nchoosek(repmat(1:n, 1, n), k), 'rows')
我得到:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
如何找到所有有重复但没有相同数字重复的组合?
有 n 种球,取 k,你有 nk 组合,在 MATLAB 中计算为 count = n^k
.
您可以使用 ndgrid
列出这些组合:
n = 3;
k = 2;
l = repmat({1:n},k,1); % k repetitions of the n balls
[l{:}] = ndgrid(l{:}); % find all combinations
l = cellfun(@(e)e(:),l,'uniformoutput',false); % make each l{i} a vector
l = [l{:}]; % turn into a single vector
现在您可以验证 size(l,1) == n^k
。
与 OP 中使用 nchoosek
和 repmat
的代码相比,此代码的优势在于不会生成重复组合,因此此代码应使用较大的 [=17= 值] 和 n
比 OP 中的代码。
对问题的编辑表明不应单独计算同一子集的排列。您可以按如下方式过滤列表 l
以删除同一组球的排列:
l = unique(sort(l,2),'rows');