如何找到对对的所有组合 [英] How to find all combinations of sets of pairs
问题描述
我想生成由3个男人和2个女人组成的对的所有组合.配对有很多示例( eg 参见
I want to generate all combinations of sets of pairs of 3 men and 2 women. There are many examples for pairing (e.g see this), but none of them deals with sets of pairs.
例如,如果我有:
Men = {'M1', 'M2'};
Women = {'W1', 'W2', 'W3'};
我想要的结果是以下几组:
The result I want is the following sets:
(M1, W1), (M2, W2)
(M1, W1), (M2, W3)
(M1, W2), (M2, W1)
(M1, W2), (M2, W3)
(M1, W3), (M2, W1)
(M1, W3), (M2, W2)
谢谢.
推荐答案
实际上很简单.要填充一组 k 对,您需要 k 个男人和 k 个女人,所以让我们找到 k 的所有可能组合em>男性和 k 女性优先:
Actually it's quite simple. To populate a set of k pairs, you need k men and k women, so let's find all possible combinations of k men and k women first:
%// Find all possible combinations of sets of k pairs of men and women
k = 2;
idx_m = nchoosek(1:numel(Men), k); % // Indices of men
idx_w = nchoosek(1:numel(Women), k); % // Indices of women
idx_w = reshape(idx_w(:, perms(1:k)), [], k); % // All permutations
然后让我们构造 k 个男性和 k 个女性的所有可能组合:
Then let's construct all possible combinations of sets of k men and k women:
[idx_comb_w, idx_comb_m] = find(ones(size(idx_w , 1), size(idx_m , 1)));
idx = sortrows([idx_m(idx_comb_m(:), :), idx_w(idx_comb_w(:), :)]);
idx = idx(:, reshape(1:size(idx, 2), k, [])'); %'// Rearrange in pairs
结果矩阵idx
包含集合中男性和女性的索引(第一列是男性,第二列-女性,第三列-男性,第四列-女性,依此类推...). /p>
示例
The resulting matrix idx
contains the indices of men and women in the sets (first column is men, second column - women, third column - men, and fourth column - women, and so on...).
Men = {'M1', 'M2'};
Women = {'W1', 'W2', 'W3'};
%// Find all possible combinations of sets of k pairs of men and women
k = 2;
idx_m = nchoosek(1:numel(Men), k);
idx_w = nchoosek(1:numel(Women), k);
idx_w = reshape(idx_w(:, perms(1:k)), [], k);
[idx_comb_w, idx_comb_m] = find(ones(size(idx_w , 1), size(idx_m , 1)));
%// Construct pairs from indices and print sets nicely
idx = sortrows([idx_m(idx_comb_m(:), :), idx_w(idx_comb_w(:), :)]);
idx = idx(:, reshape(1:size(idx, 2), k, [])');
%// Obtain actual sets
sets = cell(size(idx));
sets(:, 1:2:end) = Men(idx(:, 1:2:end));
sets(:, 2:2:end) = Women(idx(:, 2:2:end));
%// Print sets nicely
sets_t = sets';
fprintf([repmat('(%s, %s), ', 1, k - 1), '(%s, %s)\n'], sets_t{:})
在这里,结果数组sets
已被调整为包括Men
和Women
的实际值.结果是:
Here the resulting array sets
is already adapted to include the actual values from Men
and Women
. The result is:
(M1, W1), (M2, W2)
(M1, W1), (M2, W3)
(M1, W2), (M2, W1)
(M1, W2), (M2, W3)
(M1, W3), (M2, W1)
(M1, W3), (M2, W2)
这篇关于如何找到对对的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!