# Selecting Elements from a List that Doesn't Exist?

I found this function in R that can return the "power set" for a set of letters:

``````f <- function(set) {
n <- length(set)
lapply( 1:2^n-1, function(u) set[ bitwAnd(u, masks) != 0 ] )
}

results = f(LETTERS[1:3])

[]
character(0)

[]
 "A"

[]
 "B"

[]
 "A" "B"

[]
 "C"

[]
 "A" "C"

[]
 "B" "C"

[]
 "A" "B" "C"
``````

As an example, suppose I were to generate some random sequence of letters:

``````> random = sample.int(length(results), 1)
 6

> results[random]
[]
 "A" "C"
``````

Suppose now I want to make a list of the power set for all 26 letters: I know that this list would have 2^26 = 67108864 elements. There is no way that I would be able to store such a large list in the local R environment!

``````# too big
big_results = f(LETTERS[1:26])
``````

But suppose I were to generate some random number:

``````big_random = sample.int(67108864, 1)

13626980
``````
• Is there some way of knowing which permutation of letters the "big_random" would correspond to on the "big_results" list - without actually fully running "big_results"?

For example:

``````# too big to run (hypothetical list)
big_results[big_random]
``````
• Could some enumeration or recursion formula be used to figure out some pattern and then somehow determine that "13626980" corresponds to the letters "P H R T L D U Z" for instance?

Thank you!

I don't fully understand how the function works, what with that `bitwAnd()`, but its structure is relatively clear: the `lapply()` acts as a loop to generate the result. So you can easily avoid running the `lapply()` and only compute it's second argument for a given value of `u`.

1 Like