impl ch10 recursive

This commit is contained in:
ivan 2018-12-19 15:25:10 +08:00
parent 7f9d32df0f
commit f5aeb9af01
2 changed files with 40 additions and 0 deletions

View File

@ -0,0 +1,23 @@
package ch10_recursive
import scala.collection.mutable
object RecursiveDemo {
def calculateStepWays(steps: Int): Int = {
//use knownResults to avoid duplicated computing
val knownResults = mutable.HashMap.empty[Int, Int]
steps match {
case 1 => 1
case 2 => 2
case _ => knownResults.get(steps) match {
case Some(result) => result
case None => {
val result = calculateStepWays(steps - 1) + calculateStepWays(steps - 2)
knownResults.put(steps, result)
result
}
}
}
}
}

View File

@ -0,0 +1,17 @@
package ch10_recursive
import org.scalatest.{FlatSpec, Matchers}
class RecursiveDemoTest extends FlatSpec with Matchers {
behavior of "RecursiveDemoTest"
it should "calculateStepWays" in {
RecursiveDemo.calculateStepWays(1) should equal(1)
RecursiveDemo.calculateStepWays(2) should equal(2)
RecursiveDemo.calculateStepWays(3) should equal(3)
RecursiveDemo.calculateStepWays(4) should equal(5)
RecursiveDemo.calculateStepWays(5) should equal(8)
}
}