I discuss here a generic approach to solve all similar type of questions like this one. First let's see how the solutions evolve with increasing number of N to find out the general patterns.
First, the solution for length 1 is
0
1
Now for length 2, the solution becomes (2nd column separated by |):
0 | 0 0, 0 1
1 | 1 0, 1 1
Comparing it with previous solution for length 1, it is obvious that to obtain this new solution we simply append 0 and 1 to each of the previous solution (1st column, 0 and 1).
Now for length 3, the solution is (3rd column):
0 | 0 0 | 0 0 0, 0 0 1
1 | 1 0 | 1 0 0, 1 0 1
| 0 1 | 0 1 0, 0 1 1
| 1 1 | 1 1 0, 1 1 1
Again, this new solution is obtained by appending 0 and 1 to each of the previous solution (2nd column for length 2).
This observation naturally leads to a recursive solution. Assume we have already obtained our solution for length N-1 solution(c(0,1), N-1)
, to obtain solution of N we simply append 0 and 1 to each item of the solution N-1 append_each_to_list(solution(c(0,1), N-1), c(0,1))
. Notice here how a more complex problem (solving N) is naturally decomposed to a simpler problem (solving N-1).
Then we just need to translate this plain English to R code almost literally:
# assume you have got solution for a shorter length len-1 -> solution(v, len-1)
# the solution of length len will be the solution of shorter length appended with each element in v
solution <- function(v, len) {
if (len<=1) {
as.list(v)
} else {
append_each_to_list(solution(v, len-1), v)
}
}
# function to append each element in vector v to list L and return a list
append_each_to_list <- function(L, v) {
purrr::flatten(lapply(v,
function(n) lapply(L, function(l) c(l, n))
))
}
To call the function:
> solution(c(1,0), 3)
[[1]]
[1] 1 1 1
[[2]]
[1] 0 1 1
[[3]]
[1] 1 0 1
[[4]]
[1] 0 0 1
[[5]]
[1] 1 1 0
[[6]]
[1] 0 1 0
[[7]]
[1] 1 0 0