Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

listing all subsets of a vector for a given size

The function choose(n,k) tells us how many subsets of size k exists for a set of n distinct elements. Suppose I need to actually list those subsets, how I create it? in other words I'm looking for a function that accepts a vector x (of length n) and a number k and returns a list of vectors, each of size k, with subsets of x. the length of the list should be, of course, choose(length(x),k). for example

enum.choose = function(x,k) {
    # implementation should go here
{

enum.choose(1:3,2)

# should be:
# [[1]]
#    1  2
# [[2]]
#    1  3
# [[3]]
#    2  3
like image 711
amit Avatar asked May 10 '14 20:05

amit


People also ask

How do I get all the subsets of an array?

First, print the subset (output array) that has been sent to the function and then run a for loop starting from the 'index' to n-1 where n is the size of the input array. We use a loop to demonstrate that we have exactly n number of choices to choose from when adding the first element to our new array.

How do you print all subsets in Python?

Step 1: Run a loop till length+1 of the given list. Step 2: Run another loop from 0 to i. Step 3: Slice the subarray from j to i.

How do I generate all subsets in C++?

We can generate all possible subset using binary counter. For example: Consider a set 'A' having elements {a, b, c}. So we will generate binary number upto 2^n - 1 (as we will include 0 also).


1 Answers

EDIT


I realized that combn(1:3, 2, simplify = FALSE) gives you the list result you're looking for. If @Ramnath wishes to post an answer, this one will be deleted.

> combn(1:3, 2, simplify = FALSE)
## [[1]]
## [1] 1 2

## [[2]]
## [1] 1 3

## [[3]]
## [1] 2 3

So using an *apply function on it will make the following function irrelevant.


Original


Making use of the comment from @Ramnath, your function might be something like this:

enum.choose <- function(x, k) {
  if(k > length(x)) stop('k > length(x)')
  if(choose(length(x), k)==1){
    list(as.vector(combn(x, k)))
  } else {
    cbn <- combn(x, k)
    lapply(seq(ncol(cbn)), function(i) cbn[,i])
  }
}

Test runs:

> enum.choose(1:3, 2)
# [[1]]
# [1] 1 2
# 
# [[2]]
# [1] 1 3
# 
# [[3]]
# [1] 2 3
> enum.choose(c(1, 2, 5, 4), 3)
# [[1]]
# [1] 1 2 5
# 
# [[2]]
# [1] 1 2 4
# 
# [[3]]
# [1] 1 5 4
# 
# [[4]]
# [1] 2 5 4
> enum.choose(1:4, 4)
# [[1]]
# [1] 1 2 3 4
> enum.choose(1:5, 6)
# Error in enum.choose(1:5, 6) : k > length(x)
like image 187
Rich Scriven Avatar answered Oct 27 '22 00:10

Rich Scriven