/* Computes the nth Fibonacci number several ways & compares their running times. */ fun main(args: Array) { val n = 43 test(n, "dpFib", ::dpFib) test(n, "memFib", ::memFib) test(n, "naiveFib", ::naiveFib) } /* Test harness. */ fun test(n: Int, fname: String, f: (Int) -> Int) { var result = 0 val exeTime = kotlin.system.measureTimeMillis { result = f(n) } println("Running $fname($n) gives $result and it takes $exeTime ms to execute.") } ///////////////////////////////////////////////////////////////////////////// /* Computes the nth Fibonacci number using the recurrence naively. */ fun naiveFib(n: Int): Int = if (n < 2) n else naiveFib(n-1) + naiveFib(n-2) ///////////////////////////////////////////////////////////////////////////// /* Computes the nth Fibonacci number using bottom-up dynamic programming. */ fun dpFib(n: Int): Int { val table = IntArray(n+1) { it } for (i in 2..n) table[i] = table[i-1] + table[i-2] return table[n] } ///////////////////////////////////////////////////////////////////////////// /* Computes the nth Fibonacci number using memoization. */ fun memFib(n: Int): Int { val UNKNOWN = -1 val table = IntArray(n+1) { if (it < 2) it else UNKNOWN } fun accessTable(k: Int): Int { if (table[k] == UNKNOWN) table[k] = accessTable(k-1) + accessTable(k-2) return table[k] } return accessTable(n) }