所有可能的数字组合,总计为特定数量,返回数字名称

时间:2020-02-10 16:37:28

标签: r

具有以下R代码,我希望获得植物名称的所有可能组合,这些植物名称的生长持续时间(植物字符串中的数字)加起来等于总生长持续时间(anbaudauer)。允许重复植物,例如c('petersilie',2,'petersilie',2,'petersilie',2,'petersilie',2,'petersilie',2,'petersilie',2)是有效输出。 当前代码如下:

anbaudauer <- 12
w <- c(
  'tomaten_6',
  'karotten_4',
  'paprika_7',
  'erdbeeren_5',
  'koriander_2',
  'salat_3',
  'zucchini_4',
  'gurke_5',
  'petersilie_2',
  'radieschen_3'
)
#first drop the text before the '_' 
w_int <- as.integer(gsub(pattern = ".*_", replacement = "", w))
#repeat the replacement for the numbers at the end to get the vegetable names
w_names <- gsub(pattern = '_[0-9]*$', "", w)
#assign the vegetable names to the Anbaudauer-vector as names 
names(w_int) <- w_names 
w_int

myfun <- function(V, target) {
  V <- sort(V)
  mincombs <- min(which(cumsum(V) > target))
  Combs <- combn(V, mincombs)
  ans <- mapply(function(x,y) ifelse(y > 0, paste0(paste0(Combs[1:y,x], collapse="+"), "=", target), NA), 1:ncol(Combs), apply(Combs, 2, function(I) which(cumsum(I) == target)))
  ans <- unlist(ans[lengths(ans) > 0])
  return(ans)
}
myfun(V=w_int, target=anbaudauer)

然而,这仅给出了忽略例如的组合。 “ petersilie”和“ koriander”的值为2,并使用数字显示组合。如何考虑'petersilie'和'koriander'具有相同的值并获得名称而不是数字作为输出?可能的组合数量为103。 相应的python函数所需的输出看起来像[['tomaten', 6, 'tomaten', 6], ['tomaten', 6, 'karotten', 4, 'koriander', 2], ['tomaten', 6, 'karotten', 4, 'petersilie', 2], ['tomaten', 6, 'koriander', 2, 'koriander', 2, 'koriander', 2]...]

0 个答案:

没有答案
相关问题