Created
March 31, 2023 16:25
-
-
Save lucaspg96/4b10080d0be241a2b1566b1e4618eade to your computer and use it in GitHub Desktop.
An interesting way to use traits to enerate test cases in Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.scalatest.flatspec.AnyFlatSpec | |
import org.scalatest.matchers.should | |
import scala.annotation.tailrec | |
import scala.concurrent.{Await, Future} | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent.duration._ | |
import math.{pow, sqrt} | |
trait FibTest extends AnyFlatSpec with should.Matchers { | |
def solutionName: String | |
def fib(n: Int): Long | |
solutionName should "compute correctly the value for 0 and 1" in { | |
fib(0) should be(0) | |
fib(1) should be(1) | |
} | |
it should "compute correctly the value for 2" in { | |
fib(2) should be(1) | |
} | |
it should "compute correctly the value for 10" in { | |
fib(10) should be(55) | |
} | |
it should "compute correctly the value for 100 within 10s" in { | |
val futureResult = Future(fib(100)) | |
val result = Await.result(futureResult, 10.seconds) | |
result should be(3736710778780434371L) | |
} | |
} | |
class RecursiveSolutionTest extends FibTest { | |
override def solutionName: String = "Recursive solution" | |
def fib(n: Int): Long = n match { | |
case 0 => 0 | |
case 1 => 1 | |
case n => | |
val x = fib(n-1) | |
val y = fib(n-2) | |
x + y | |
} | |
} | |
class TailRecSolutionTest extends FibTest { | |
override def solutionName: String = "Tail recursive solution" | |
@tailrec | |
final def tailRec(n: Int, a: Long = 0, b: Long = 1): Long = { | |
if(n == 0) a | |
else if (n == 1) b | |
else tailRec(n-1, b, a+b) | |
} | |
def fib(n: Int): Long = tailRec(n) | |
} | |
class FormulaSolutionTest extends FibTest { | |
override def solutionName: String = "Formula solution" | |
def fib(n: Int): Long = { | |
val fi = (1+sqrt(5))/2 | |
val psi = (1-sqrt(5))/2 | |
((pow(fi,n) - pow(psi,n))/sqrt(5)).toLong | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment