带有两个参数的函数,当参数相等时返回

时间:2018-03-28 16:08:46

标签: r function iteration multiple-arguments

我正在尝试创建一个带有两个参数的函数。在我的情况下,它将重复调用第一个参数

f()

直到f连续返回相同的值3x。然后它将调用第二个参数

g()

并且如果g返回与先前返回的f相同的值,则该函数必须返回此值。否则它将返回并再次调用第一个参数f()并重复循环。

这是我到目前为止所拥有的。

call_until = function(f, g) {
    while(1) {
        n = f %>% chunk(3) %>% filter(f, function(v) length(unique(v)) == 1)
        x = n()[1]
        if (x == g()) {
            return(x)
        }
    }
}

例如,如果f连续三次返回4,则转到g。如果g等于连续三次返回的f(在本例中为4);所以如果g == 4,那么call_until应该返回4.

3 个答案:

答案 0 :(得分:0)

以下是如何实施的示例:

f <- function(){
  return(sample(1:10,1))
}
g <- f

call_until <- function(f, g){
  results <- c(f(), f(), f())
  test <- g()
  while(length(unique(results)) > 1 || test != results[3]){
    results <- c(results[2:3], f())
    test <- g()
  }
  return(test)
}

现在我在这里创建了一些简单的函数f;g,它们将在1-10之间随机选择(甚至不需要参数作为输入)。所以这可能需要进行调整。以下是一些输出:

> call_until(f,g)
[1] 3
> call_until(f,g)
[1] 7
> call_until(f,g)
[1] 10
> call_until(f,g)
[1] 9

答案 1 :(得分:0)

递归函数可能不是最佳选择,请将此答案视为一种选择。

f <- function(){
    sample(1:2, 1)
}

g <- function(){
    sample(1:2, 1)
}

fg <- function(f, g){
    res <- c(replicate(3, f()), g()) 
    message(paste("[-] f():", paste(res[1:3], collapse = ","), 
                  "g():", res[4], "\n"))
    if(var(res) == 0){
        message(paste("[+] Magic value is ", res[1]))
        return(invisible(res[1]))
    }
    return(fg(f, g))
}

fg(f,g)

[-] f(): 1,1,1 g(): 2 

[-] f(): 1,1,1 g(): 2 

[-] f(): 1,2,2 g(): 1 

[-] f(): 2,1,1 g(): 2 

[-] f(): 1,1,1 g(): 2 

[-] f(): 1,2,2 g(): 1 

[-] f(): 1,1,1 g(): 1 

[+] Magic value is  1

答案 2 :(得分:0)

这是另一个如何做到这一点的例子

call_until = function(f, g) {
  while(TRUE) {
    value <- f()
    seen <- 1
    while(seen < 3) {
      next_value <- f()
      if (next_value == value) {
        seen <- seen + 1
      } else {
        value <- next_value
        seen <- 1
      }
    }
    if (value == g()) {
        return(value)
    }
  }
}

虽然如果f不匹配或只有一个新值,您应该绘制三个新的g值,这很重要。

以下是一些有用的测试功能。它们只是按顺序从向量中返回值,并根据需要重复。

cycler <- function(vals) {
  i <- 1
  function() {
    i<<-i+1
    vals[(i-2) %% length(vals)+1]
  }
}

f <- cycler(c(1,2,2,2,3,4,5,5,5,1,1))
g <- cycler(c(5,4))

有了这个我们得到

call_until(f, g)
# [1] 5
相关问题