K great combination of size p without replacement

From integers 1,...,NI would like to take k random different combinations without repeating the size p. For example, if N=10, k=4and p=3, a possible result:

1 4 9
9 4 2
3 5 2
1 8 4

But not:

1 4 9
9 4 2
3 5 3
1 9 4

For two reasons:

  • [1 4 9]and [1 9 4]- the same combination.

  • [3 5 3] no repetition.

Note that getting all possible combinations and (random) choosing kthem easily develops into memory problems.

+4
source share
1 answer

Ok, I found a solution that works for me. My main concerns:

  • I want combinations to kbe random.
  • .

p ( row = randperm(N,p)) , .

k . k . , , - N = 10^6, k = 2000, p = 10, 1 .

, , .

function C = kcombsn(N,k,p)
    C       = randperm(N,p);
    Csort   = sort(C,2);

    while size(C,1) < k

        row = randperm(N,p);
        row_sort = sort(row);

        if isempty(intersect(row_sort,Csort,'rows'))
            C = [C; row];
            Csort = [Csort; row_sort];
        end
    end

end

Edit: MATLAB.

+4

Source: https://habr.com/ru/post/1624100/


All Articles