impl ch10 recursive
This commit is contained in:
parent
7f9d32df0f
commit
f5aeb9af01
23
scala/src/main/scala/ch10_recursive/RecursiveDemo.scala
Normal file
23
scala/src/main/scala/ch10_recursive/RecursiveDemo.scala
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
17
scala/src/test/scala/ch10_recursive/RecursiveDemoTest.scala
Normal file
17
scala/src/test/scala/ch10_recursive/RecursiveDemoTest.scala
Normal 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)
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user