功能输出两个输出,其中需要 1

Function Outputting Two outputs where 1 is required

我的代码当前进行 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)

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

您可以只将所有答案存储在一个列表中,并且仅 return 该列表的第一个元素。

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)

整数规划可用于获得紧凑的解决方案。它 returns 一个由 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