group same sets

grouping the same bit strings
mail@pastecode.io avatar
unknown
r
2 years ago
926 B
2
Indexable
Never
sets <- matrix(c(
  1, 1, 0, 0, 1,
  0, 0, 0, 0, 1,
  1, 1, 1, 1, 0,
  0, 1, 1, 1, 1
), nrow = 5, ncol = 4)

numberingseq <- function(mats) {
  samesets <- list()
  q <- list(c(1, seq(nrow(mats))))

  while (length(q) > 0) {
    inds <- q[[1]]
    q <- q[-1]
    n <- inds[1]
    inds <- inds[-1]
    zeros <- c(n + 1) # First element indicates the column to look at
    ones <- c(n + 1)

    for (i in inds) {
      if (mats[i, n] == 0) zeros <- c(zeros, i)
      if (mats[i, n] == 1)   ones <- c(ones, i)
    }
    if (n == ncol(mats)) {
      zeros <- zeros[-1]
      ones <- ones[-1]
      if (length(zeros > 0)) samesets <- append(samesets, list(zeros))
      if (length(ones > 0))  samesets <- append(samesets, list(ones))
    } else {
      if (length(ones) > 1) q <- append(q, list(ones))
      if (length(zeros) > 1)   q <- append(q, list(zeros))
    }
  }
  return(samesets)
}
samesets <- numberingseq(sets)
samesets