From f5aeb9af01aa1b4b5ba2becccd8e7cb1a3fe365d Mon Sep 17 00:00:00 2001 From: ivan Date: Wed, 19 Dec 2018 15:25:10 +0800 Subject: [PATCH] impl ch10 recursive --- .../scala/ch10_recursive/RecursiveDemo.scala | 23 +++++++++++++++++++ .../ch10_recursive/RecursiveDemoTest.scala | 17 ++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 scala/src/main/scala/ch10_recursive/RecursiveDemo.scala create mode 100644 scala/src/test/scala/ch10_recursive/RecursiveDemoTest.scala diff --git a/scala/src/main/scala/ch10_recursive/RecursiveDemo.scala b/scala/src/main/scala/ch10_recursive/RecursiveDemo.scala new file mode 100644 index 0000000..50613eb --- /dev/null +++ b/scala/src/main/scala/ch10_recursive/RecursiveDemo.scala @@ -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 + } + } + } + } +} diff --git a/scala/src/test/scala/ch10_recursive/RecursiveDemoTest.scala b/scala/src/test/scala/ch10_recursive/RecursiveDemoTest.scala new file mode 100644 index 0000000..1987ece --- /dev/null +++ b/scala/src/test/scala/ch10_recursive/RecursiveDemoTest.scala @@ -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) + } + +}