尝试计算Ackermann时堆栈溢出

时间:2014-07-07 20:56:02

标签: scala intellij-idea stack-overflow ackermann

作为实验的一部分,我想了解使用和不使用缓存/记忆时计算Ack(0,0)Ack(4,19)需要多长时间。但是我一直遇到一个简单的绊脚石...我的堆栈一直在溢出。

这是我的代码:

import org.joda.time.{Seconds, DateTime}
import scala.collection.mutable

// Wrapper case class to make it easier to look for a specific m n combination when using a Map 
// also makes the code cleaner by letting me use a match rather than chained ifs
case class Ack(m: Int, n: Int)

object Program extends App {
  // basic ackermann without cache; reaches stack overflow at around Ack(3,11)
  def compute(a: Ack): Int = a match {
    case Ack(0, n) => n + 1
    case Ack(m, 0) => compute(Ack(m - 1, 1))
    case Ack(m, n) => compute(Ack(m - 1, compute(Ack(m, n - 1))))
  }

  // ackermann WITH cache; also reaches stack overflow at around Ack(3,11)
  def computeWithCache(a: Ack, cache: mutable.Map[Ack, Int]): Int = if(cache contains a) {
    val res = cache(a)
    println(s"result from cache: $res")
    return res // explicit use of 'return' for readability's sake
  } else {
    val res = a match {
      case Ack(0, n) => n + 1
      case Ack(m, 0) => computeWithCache(Ack(m - 1, 1), cache)
      case Ack(m, n) => computeWithCache(Ack(m - 1, computeWithCache(Ack(m, n - 1), cache)), cache)
    }
    cache += a -> res
    return res
  }

  // convenience method
  def getSeconds(start: DateTime, end: DateTime): Int = 
    Seconds.secondsBetween(start, end).getSeconds

  val time = DateTime.now
  val cache = mutable.Map[Ack, Int]()

  for{ 
    i <- 0 to 4
    j <- 0 until 20
  } println(s"result of ackermann($i, $j) => ${computeWithCache(Ack(i, j), cache)}. Time: ${getSeconds(time, DateTime.now)}")
}

我使用Scala和SBT插件在IntelliJ Idea 13.1.3中运行Scala 2.11.1。

我能做些什么来不在Ack周围堆叠溢出(3,11)?

我已经尝试将javacOptions += "-Xmx2G"添加到我的build.sbt中,但它似乎只会让问题变得更糟。

0 个答案:

没有答案