编写嵌套if-else语句的更好方法

时间:2018-03-30 12:13:41

标签: scala if-statement nested

编写以下逻辑的Scala方法是什么?

def collatzAlgorithm(target: Int): Int = {
    if (target % 2 == 0) {
      val new_target = target / 2
      if (new_target == 1) {
        new_target
      } else {
        if (new_target % 2 != 0) {
          new_target * 3 + 1
        } else {
          new_target
        }
      }
    } else {
      target
    }
  }

感谢!!!!

2 个答案:

答案 0 :(得分:1)

scala方式并不是因为它需要简化和展平你的嵌套。我会把它重构为:

val newTarget = target / 2
if (newTarget % 2 == 0) {
  newTarget
} else if (newTarget != 1) {
  newTarget * 3 + 1
} else {
  1
}

然而,很难说这实际上是否符合您的想法,因为您会混淆地试图提前一步。我会写一个类似于:

的拼贴序列
Iterator.iterate(n){n => if (n % 2 == 0) n / 2 else 3 * n + 1}.takeWhile{_ != 1}

结束于2,但如果您确实需要++ Iterator(1),则可以添加1

答案 1 :(得分:0)

您的代码产生了错误的结果:

(1 to 10).map (collatzAlgorithm)
// Vector(1, 1, 3, 2, 5, 10, 7, 4, 9, 16)

所有奇数值都没有改变。这是一个有效的解决方案:

def collatzAlgorithm (target: Int): Int = {
    if (target == 1) 1
    else target % 2 match {
        case 0 => target / 2 
        case 1 => target * 3 + 1
    }
}   

(1 to 10).map (collatzAlgorithm)
// Vector(1, 1, 10, 2, 16, 3, 22, 4, 28, 5)

您可以考虑使用递归算法,该算法立即调用下一步:

def collatz (target: Int): Int = {
    if (target == 1) 1
    else target % 2 match {
        case 0 => collatz (target / 2)
        case 1 => collatz (target * 3 + 1)
    }
} 

哪种方法适用于小值:

(1 to 10).map (collatz)
// Vector(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)

然而 - 对于更大和更多的输入,一次又一次地计算相同的序列,因此分辨率应该与某种记忆一起使用以避免这种低效率。