【问题标题】:Function Outputting Two outputs where 1 is required功能 输出 需要 1 的两个输出
【发布时间】:2021-03-31 22:11:25
【问题描述】:

我的代码目前正在掷 4 次骰子,如果它们的总和为 8,则将值更改为 8。

我的函数能够根据需要正确地将 (1,3,4,5) 更改为 (5,8)。但是,如果我的骰子掷骰是(1,2,6,5),例如,我会遇到一个问题,因为可以进行 8 的两种组合。例如(可以使用 6,2 或 1,2,5)。我需要我的代码只输出这些解决方案之一,但我不知道如何做到这一点。

   target2 <- function(x)
   {
   roll <- (x)
   library(dplyr)

    comboes <- Reduce( f=append, lapply( 2:4, function(m)combn(x=roll, m=m) %>% as.data.frame %>% 
    as.list  ) )

    i.is.eight <- which( sapply( comboes, sum ) == 8 )

    check <- c(i.is.eight) 

    if((length(check) == 0))
  return(roll)
   else if( length(check) >= 1 ){
   lapply( i.is.eight,function(i) {
  
  roll.i <- comboes[[i]]
  
  ## base is the dice that did not take part in the sum
  base <- roll
  for( r in roll.i ) {
    base <- base[ -match( r, base ) ]
  }
  
  
  answer <- c( base, 8 )
  

  return(answer)
  
}) %>% unique
} 
}

 (   x <-sample(1:6, 4, replace=TRUE))
  target2(x)

我知道我的代码不是最清楚的,所以很乐意解释。任何帮助将不胜感激。

【问题讨论】:

  • 您可以使用set.seed(n) 设置一个案例来说明您的查询吗?
  • 看,有一个类似的任务。也许会有所帮助stackoverflow.com/questions/66857586/…
  • 即使是您的工作示例(1,3,4,5) -&gt; (5,8)(1,4,8) 也不能成为解决方案吗?因此,您的代码在某些情况下可以使用多种解决方案...

标签: r dice


【解决方案1】:

您可以将所有答案存储在一个列表中,然后返回该列表的第一个元素。

target2 <- function(x)
{
  roll <- (x)
  library(dplyr)
  
  comboes <- Reduce( f=append, lapply( 2:4, function(m)combn(x=roll, m=m) %>% as.data.frame %>% 
                                         as.list  ) )
  
  i.is.eight <- which( sapply( comboes, sum ) == 8 )
  
  check <- c(i.is.eight) 
  
  if((length(check) == 0))
    return(roll)
  else if( length(check) >= 1 ){
    answers <-lapply( i.is.eight,function(i) {
      
      roll.i <- comboes[[i]]
      
      ## base is the dice that did not take part in the sum
      base <- roll
      for( r in roll.i ) {
        base <- base[ -match( r, base ) ]
      }
      
      
      answer <- c( base, 8 )
      
      
      return(answer)
      
    }) 
    return(answers[[1]])
  } 
}

(   x <-sample(1:6, 4, replace=TRUE))
target2(x)

【讨论】:

    【解决方案2】:

    整数规划可用于获得紧凑的解决方案。它返回一个由 0 和 1 组成的向量,选出 x 的子集,总和为 8,否则如果不存在解,则为 NA。

    library(lpSolve)
    
    x <- c(1, 2, 5, 3) # test input
    
    with(lp("min", 0*x, t(x), "==", 8, all.bin = TRUE), if (status == 0) solution else NA)
    ## [1] 1 1 1 0
    

    【讨论】:

      猜你喜欢
      • 2014-02-10
      • 1970-01-01
      • 2023-01-22
      • 2018-10-05
      • 2018-12-25
      • 2016-09-29
      • 1970-01-01
      • 2020-05-27
      • 1970-01-01
      相关资源
      最近更新 更多