大小为K的整数分区

时间:2018-01-20 09:54:29

标签: r algorithm combinatorics

给定v个非负整数的向量F,我想逐个创建大小为K的所有F个向量集合是v。我称C为这些K向量的矩阵; C的行和得v

例如,大小为F = 2的向量(1,2),如果我们设置K = 2,则可以分解为:

# all sets of K vectors such that their sum is (1,2)
C_1 = 1,0   C_2 = 1,0  C_3 = 1,0 C_4 =  0,1   C_5 = 0,1  C_6 = 0,1
      2,0         1,1        0,2        2,0         1,1        0,2

目标是为每个可能的C应用一些函数。目前,我使用此代码,我预先计算所有可能的C然后通过它们。

library(partitions)
K <- 3
F <- 5
v <- 1:F

partitions <- list()
for(f in 1:F){
  partitions[[f]] <- compositions(n=v[f],m=K)
}

# Each v[f] has multiple partitions. Now we create an index to consider
# all possible combinations of partitions for the whole vector v.
npartitions <- sapply(partitions, ncol)
indices <- lapply(npartitions, function(x) 1:x)
grid <- as.matrix(do.call(expand.grid, indices)) # breaks if too big

for(n in 1:nrow(grid)){
  selected <- c(grid[n,])
  C <- t(sapply(1:F, function(f) partitions[[f]][,selected[f]]))

  # Do something with C
  #...
  print(C)
}

然而,当尺寸太大时,F,K很大,那么组合的数量会爆炸,而expand.grid无法解决这个问题。

我知道,对于给定位置v [f],我可以一次创建一个分区

partition <- firstcomposition(n=v[f],m=K)
nextcomposition(partition, v[f],m=K)

但是如何使用它来生成所有可能的C,如上面的代码?

1 个答案:

答案 0 :(得分:1)

{this.state.isVisible?<ModalComponent />:null}

您可以避免生成npartitions <- ...... indices <- lapply(npartitions, function(x) 1:x) grid <- as.matrix(do.call(expand.grid, indices)) ,并借助Cantor expansion依次生成其行。

这是返回整数grid的Cantor展开的函数:

n

例如:

aryExpansion <- function(n, sizes){
  l <- c(1, cumprod(sizes))
  nmax <- tail(l,1)-1
  if(n > nmax){
    stop(sprintf("n cannot exceed %d", nmax))
  }
  epsilon <- numeric(length(sizes))
  while(n>0){
    k <- which.min(l<=n)
    e <- floor(n/l[k-1])
    epsilon[k-1] <- e
    n <- n-e*l[k-1]
  }
  return(epsilon)
}

所以,而不是生成网格:

expand.grid(1:2, 1:3)
##   Var1 Var2
## 1    1    1
## 2    2    1
## 3    1    2
## 4    2    2
## 5    1    3
## 6    2    3
aryExpansion(0, sizes = c(2,3)) + 1
## [1] 1 1
aryExpansion(1, sizes = c(2,3)) + 1
## [1] 2 1
aryExpansion(2, sizes = c(2,3)) + 1
## [1] 1 2
aryExpansion(3, sizes = c(2,3)) + 1
## [1] 2 2
aryExpansion(4, sizes = c(2,3)) + 1
## [1] 1 3
aryExpansion(5, sizes = c(2,3)) + 1
## [1] 2 3

您可以这样做:

npartitions <- ......
indices <- lapply(npartitions, function(x) 1:x)
grid <- as.matrix(do.call(expand.grid, indices))
for(n in 1:nrow(grid)){
  selected <- grid[n,]
  ......
}