Collat​​z - 最大步数和对应的步数

Collatz - maximum number of steps and the corresponding number

我正在尝试编写一个 Scala 函数,该函数将上限作为参数并计算从 1 到该上限范围内的数字的步长。它必须 return 最大步骤数和需要那么多步骤的相应数量。 (成对 - 第一个元素是步数,第二个是相应的索引)

我已经创建了一个名为 "collatz" 的函数来计算步数。我是 Scala 的新手,由于限制,我有点卡住了。这是我想启动该功能的方式:

def max(x:Int):Int = {
  for (i<-(1 to x).toList) yield collatz(i) 

我认为解决此问题的方法是: 1. 遍历范围并将 collat​​z 应用于所有元素,同时将它们放入存储步数的新列表中。 2. 使用 List.max 找到新列表的最大值 3. 使用 List.IndexOf 找到索引。但是,我真的被卡住了,因为我不知道如何在不使用 var(并且只使用 val)的情况下做到这一点。谢谢!

尝试:

(1 to x).map(collatz).maxBy(_._2)._1

像这样:

def collatzMax(n: Long): (Long, Long) = {
  require(n > 0, "Collatz function is not defined for n <= 0")

  def collatz(n: Long, steps: Long): Long = n match {
    case n if (n <= 1)     => steps
    case n if (n % 2 == 0) => collatz(n / 2, steps + 1)
    case n if (n % 2 == 1) => collatz(3 * n + 1, steps + 1)
  }

  def loop(n: Long, current: Long, acc: List[(Long, Long)]): List[(Long, Long)] = 
    if (current > n) acc
    else {
      loop(n, current + 1, collatz(current, 0) -> current :: acc)
    }

  loop(n, 1, Nil).sortBy(-_._1).head
}

示例:

collatzMax(12)
result: (Long, Long) = (19,9) // 19 steps for collatz(9)

用于:

def collatzMax(n: Long) = 
  (for(i <- 1L to n) yield collatz(i) -> i).sortBy(-_._1).head

或者(继续你的想法):

def maximum(x: Long): (Long, Long) = {
  val lst = for (i <- 1L to x) yield collatz(i) 
  val maxValue = lst.max
  (maxValue, lst.indexOf(maxValue) + 1)
}