Select Next Subset
Select next subset of size k from a set of size n.
next_subset(a, n, k)
a
: a numeric vector (integers)n
: an integer: the size of the set to choose fromk
: an integer: the subset sizeGiven a subset a of size k taken from a set of size n, compute the next subset by alphabetical order.
Uses algorithm NEXKSB of Nijenhuis and Wilf (1975).
a numeric vector (the next subset) or NULL
(when there is no next subset)
Nijenhuis, A. and Wilf, H. S. (1975) Combinatorial Algorithms for Computers and Calculators. Academic Press.
Enrico Schumann
choose
computes the number of combinations
combn
creates all combinations
expand.grid
n <- 4 k <- 2 t(combn(n, k)) ## [,1] [,2] ## [1,] 1 2 ## [2,] 1 3 ## [3,] 1 4 ## [4,] 2 3 ## [5,] 2 4 ## [6,] 3 4 a <- 1:k print(a) while (!is.null(a)) print(a <- next_subset(a, n = n, k = k)) ## [1] 1 2 ## [1] 1 3 ## [1] 1 4 ## [1] 2 3 ## [1] 2 4 ## [1] 3 4
Useful links