next_subset function

Select Next Subset

Select Next Subset

Select next subset of size k from a set of size n.

next_subset(a, n, k)

Arguments

  • a: a numeric vector (integers)
  • n: an integer: the size of the set to choose from
  • k: an integer: the subset size

Details

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

Returns

a numeric vector (the next subset) or NULL

(when there is no next subset)

References

Nijenhuis, A. and Wilf, H. S. (1975) Combinatorial Algorithms for Computers and Calculators. Academic Press.

Author(s)

Enrico Schumann

See Also

choose computes the number of combinations

combn creates all combinations

expand.grid

Examples

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