【问题标题】:How to find all possible combinations of balls? [duplicate]如何找到所有可能的球组合? [复制]
【发布时间】:2019-11-08 20:16:14
【问题描述】:

我需要找到所有可能的方法来组合 k 数量的球和 n 类型的球。

假设如果有 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

如何找到所有重复但不重复相同数字的组合?

【问题讨论】:

    标签: matlab combinatorics counting


    【解决方案1】:

    使用 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 中使用 nchoosekrepmat 的代码相比,此代码的优势在于不会生成重复的组合,因此此代码应使用比代码更大的 kn 值在 OP 中。


    对问题的修改表明不应单独计算同一子集的排列。您可以按如下方式过滤列表l,以删除同一组球的排列:

    l = unique(sort(l,2),'rows');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 2011-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-27
      相关资源
      最近更新 更多