How to find all possible pairwise combinations of binary vectors where second vector conditionally depend on the first vector?

182 Views Asked by At

I want to find all the possible pairwise combination where the 1 in 2nd vector is conditioned upon where 1 is located in the first vector of the pair. If in the first vector, there is a 1 in the 2nd position, then in the second vector, 1 can be either in 2nd or 3rd position but NOT IN first.

An acceptable output for two binary vectors of length 3 each. All vectors consists of a single 1 and rest are 0:

        [,1] [,2] [,3]
  [1,]    1    0    0
  [2,]    0    1    0  

  [1,]    1    0    0
  [2,]    0    0    1

  [1,]    0    1    0
  [2,]    0    0    1

  [1,]    1    0    0
  [2,]    1    0    0

  [1,]    0    1    0
  [2,]    0    1    0

  [1,]    0    0    1
  [2,]    0    0    1

Is there any elegant way to do this?

1

There are 1 best solutions below

0
On BEST ANSWER

Any valid list of $n$ vectors, each with length $k$, can be represented by a list of $k$ nonnegative integers whose sum is $n$. Each entry in the list represents the number of ones in its corresponding column. For example,

        [,1] [,2] [,3]
  [1,]    1    0    0       --->      (1, 1, 0)
  [2,]    0    1    0  

  [1,]    0    0    1       --->      (0, 0, 2)
  [2,]    0    0    1

So, you just need to list all vectors of length $k$ summing to $n$. You can easily doing this recursively, by making all possible choices for the first entry, then recursively filling the rest. After the following pseudo code is, the collection allVectors will contain all possible vectors.

set L to a list of length k (indexed from 1 to k)
set allVectors to an empty collection

procedure listAllVectors(sumOfRemainingEntries, currentIndex):
    if currentIndex = k:
        set L[currentIndex] to sumOfRemainingEntries
        add L to allVectors
    else:
        for i in {0, 1, ... , n}:
            set L[currentIndex] to i
            do listAllVectors(sumOfEntries - i, currentIndex + 1)

do listAllVectors(n, 1)