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
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.
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.
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).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With