Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all combinations of sets of pairs

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.

For instance, if I have:

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)

Thank you.

like image 502
user2627824 Avatar asked Jan 28 '26 11:01

user2627824


1 Answers

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

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

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...).

Example

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{:})

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)
like image 175
Eitan T Avatar answered Jan 30 '26 02:01

Eitan T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!