0

Given the following vector of length n=10:

# [1] 0 0 0 0 0 1 0 0 1 0
vec <- c(0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 1L, 0L)

Suppose we want to apply the operator & to all possible combinations of the vector elements. That is:

res <- combn(n, 2, function(v) vec[v[1]]&vec[v[2]])
# total number of possible combinations is n(n-1)/2 = 45

However, we know that the result of & operator is true only when both values are 1 and hence, we can do it in a more clever way. In fact, the result of combn is a vector of length 45 with only one value of 1 and the rest are just 0.

Now the question is that how we can extract the position of the only 1 without applying the combn itself? Once we can get it, we generate the result simply as follow:

res <- rep(0, 45)
res[index] <- 1

where index is the questioned position.

989
  • 12,579
  • 5
  • 31
  • 53

1 Answers1

0

How about this (assuming that only two positions of the vector are 1, rest are zeros):

vec <- c(0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 1L, 0L)

n <- length(vec)
pos <- which(vec==1)
index = ifelse(pos[1]==1, 0, sum((n-1):(n-pos[1]+1))) + (pos[2] - pos[1])
index
#[1] 38

res <- combn(n, 2, function(v) vec[v[1]]&vec[v[2]])
which(res==TRUE)
#[1] 38
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63