如何找到所有可能的球组合? [英] How to find all possible combinations of balls?

查看:90
本文介绍了如何找到所有可能的球组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到所有可能的方法来组合n种类型的球中的k个球.

I need to find all possible ways to combine k amount of balls from n types of balls.

让我们说如果有3种球,我想拿2种,我想要的结果是:

Let's say if there are 3 types of balls and I want to take 2, result I want is:

     1     1
     1     2
     1     3
     2     2
     2     3
     3     3

我正在尝试使用以下代码行:

I am trying to do it with the following line:

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

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

How to do find all combinations with repetitions but without duplicates of same numbers?

推荐答案

n 种球,取 k ,你有 n k 组合,在MATLAB中以count = n^k计算.

With n types of balls, taking k, you have nk combinations, in MATLAB computed as count = n^k.

您可以使用 ndgrid 列出这些组合:

You can list these combinations using 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.

与使用nchoosekrepmat的OP中的代码相比,此代码的优势在于不会生成重复的组合,因此,该代码应与kn相比使用更大的值在OP中.

The advantage of this code over the one in the OP using nchoosek with repmat is that no repeated combinations will be generated, so this code should work with larger values of k and n than the code in the OP.

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

The edit to the question suggests that permutations of the same subset should not be counted separately. You can filter the list l as follows to remove permutations of the same set of balls:

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

这篇关于如何找到所有可能的球组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆