I would like to create all possible combinations of a binary vector of length n > 2
with the property that the maximum number of 1
's in the row is 2
.
For example:
If n=4
, the answer would be:
0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
1 0 0 0
1 0 0 1
1 0 1 0
1 1 0 0
This works but gets very memory intensive and slow as n gets large (n>20):
n <- 4
m <- expand.grid(rep(list(0:1),n))
m <- m[rowSums(m)<3,]
How can I do this more efficiently?
Answer:
*Based on a combination of Marat Talipov's and akrun's solutions
n=4
z=rep(0,n)
rbind(unname(z), t(combn(0:n,2, FUN=function(k) {z[k]=1;z})))
expand.grid
unnecessarily creates rows that will be removed in the next step. Preferably, these vectors wouldn't be created in the first place. – NyemanReduce("+", m)
is by several factors more efficient thanrowSums(m)
– LedouxcombnPrim
fromlibrary(grBase)
. It is very fast compared tocombn
Please check https://mcmap.net/q/541786/-faster-version-of-combn/… – Haematopoiesis