0

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

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

I get:

     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?

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120

1 Answers1

3

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

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

Now you can verify that size(l,1) == n^k.

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.


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');
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120