【问题标题】:Understanding this Collatz function code in R理解 R 中的 Collat​​z 函数代码
【发布时间】:2015-10-02 06:39:54
【问题描述】:

我是R编程语言的新手,很抱歉这种简单的问题,并且已经处理了R中的collat​​z猜想的代码。实际上,我已经完全理解了前两部分,但我不知道逻辑第 3 部分中的 while 循环以及 n.total

Part 1:

is.even <- function(x){
  if(x%%2==0){
    print("TRUE")
  }else{
    print("FALSE")
  }
}

Part 2:

collatz <- function(n){
  if (is.even(n)) {
    n/2
  }else{
      3*n+1
    }
}

Part 3:

n <- 27
n.total <- NULL
while(n != 1){
  n <- collatz(n)
  n.total <- c(n.total,n)
}

n.total

【问题讨论】:

  • 您的具体问题是什么?除了is.even() 应该返回它的结果,而不是打印它,这是破坏性的。如果您想要进行一般的代码审查,请在CodeReview 上发帖
  • 很高兴看到您加入了 Stackoverflow。教授的问候
  • @Teepeemm,好的,那么 OP 应该在哪里发布这种东西?
  • @smci “向我解释这整件事”可能不属于 StackExchange 的任何地方。 “向我解释第 3 部分”可能属于这里,尽管第 1 部分中明显的错误表明 OP 也没有真正理解这一点。不过,在这种特定情况下,OP 可能应该去他们教授的办公时间寻求帮助。

标签: r function math functional-programming collatz


【解决方案1】:
collatz <- function(n, acc=c()) {
  if(n==1) return(c(acc, 1));
  collatz(ifelse(n%%2==0, n/2, 3*n +1), c(acc, n))} 

collat​​z(5) 将返回:5 16 8 4 2 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-09
    • 2013-10-17
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多