Skip to content

Commit

Permalink
fibonacci
Browse files Browse the repository at this point in the history
  • Loading branch information
jesperancinha committed Oct 25, 2023
1 parent 1b05b72 commit 6263cca
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 0 deletions.
8 changes: 8 additions & 0 deletions jeorg-kotlin-crums/jeorg-kotlin-crums-4-variance/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@
<artifactId>mockk</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.kotest</groupId>
<artifactId>kotest-assertions-api-jvm</artifactId>
</dependency>
<dependency>
<groupId>io.kotest</groupId>
<artifactId>kotest-assertions-core-jvm</artifactId>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ class Main {
ImmutableEatingOut.main()
CupManager.main()
Patisserie.main()
WarehouseManager.main()
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package org.jesperancinha.ktd

class TailRec {
companion object {
@JvmStatic
fun main(args: Array<String> = emptyArray()) {
println(fibonnaci(5))
println(fibonnaciOptimized(5))
}

fun fibonnaci(value: Int): Int {
if (value == 2) return 1
if (value == 1) return 0
return fibonnaci(value - 1) +
fibonnaci(value - 2)
}

tailrec fun fibonnaciOptimized(value: Int,
curr: Int = 1,
sum: Int = 0): Int {
if (value == 1)
return sum
return fibonnaciOptimized(value - 1,
sum, sum + curr)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package org.jesperancinha.ktd

import io.kotest.matchers.shouldBe
import org.jesperancinha.ktd.TailRec.Companion.fibonnaci
import org.jesperancinha.ktd.TailRec.Companion.fibonnaciOptimized
import kotlin.test.Test

class TailRecTest {

@Test
fun `should calculate 1 element fibonacci`() {
fibonnaci(1) shouldBe 0
fibonnaciOptimized(1) shouldBe 0
}

@Test
fun `should calculate 2 element fibonacci`() {
fibonnaci(2) shouldBe 1
fibonnaciOptimized(2) shouldBe 1
}

@Test
fun `should calculate 3 element fibonacci`() {
fibonnaci(3) shouldBe 1
fibonnaciOptimized(3) shouldBe 1
}

@Test
fun `should calculate 4 element fibonacci`() {
fibonnaci(4) shouldBe 2
fibonnaciOptimized(4) shouldBe 2
}

@Test
fun `should calculate 5 element fibonacci`() {
fibonnaci(5) shouldBe 3
fibonnaciOptimized(5) shouldBe 3
}

@Test
fun `should calculate 9 element fibonacci`() {
fibonnaci(9) shouldBe 21
fibonnaciOptimized(9) shouldBe 21
}
}

0 comments on commit 6263cca

Please sign in to comment.