1
+ // ---------------- Fibonacci Sequence ----------------
2
+ // 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144...
3
+
4
+ class FibonacciMemoized {
5
+ private static cache = Object . create ( { } ) ;
6
+
7
+ private static _initialize = ( ( ) => {
8
+ FibonacciMemoized . cache [ 1 ] = 0 ;
9
+ FibonacciMemoized . cache [ 2 ] = 1 ;
10
+ } ) ( ) ;
11
+
12
+ public static nthTerm ( nth : number ) : number {
13
+ if ( nth in this . cache )
14
+ return this . cache [ nth ] ;
15
+ else
16
+ this . cache [ nth ] = this . nthTerm ( nth - 2 ) + this . nthTerm ( nth - 1 ) ;
17
+
18
+ return this . cache [ nth ] ;
19
+ }
20
+ }
21
+
22
+ function fibonacciBottomUp ( ) {
23
+ let fibonacciSequence : number [ ] = [ 0 , 1 ] ;
24
+
25
+ return function ( nth : number ) : number | undefined {
26
+ if ( nth < 1 ) return undefined ;
27
+ else nth = Math . floor ( nth ) ;
28
+
29
+ for ( let i = fibonacciSequence . length ; i <= nth ; ++ i )
30
+ fibonacciSequence . push ( fibonacciSequence [ i - 2 ] + fibonacciSequence [ i - 1 ] ) ;
31
+
32
+ return fibonacciSequence [ nth - 1 ] ;
33
+ }
34
+ }
35
+
36
+ function executionTime ( n : number ) : string {
37
+ const t0 = performance . now ( ) ;
38
+ console . log ( 'Term' , n + ':' , FibonacciMemoized . nthTerm ( n ) ) ;
39
+ const t1 = performance . now ( ) ;
40
+ return ( t1 - t0 ) + 'ms' ;
41
+ }
42
+
43
+ //---------------------------------------------------------------------
44
+ // ---------- MAIN PROGRAM ----------
45
+ //---------------------------------------------------------------------
46
+ if ( import . meta. main ) {
47
+
48
+ console . log ( '\n------------ Memoization ------------' ) ;
49
+ const a1 = Object . create ( { } ) ;
50
+ a1 . run_1 = executionTime ( 256 ) ;
51
+ a1 . run_2 = executionTime ( 256 ) ;
52
+ a1 . run_3 = executionTime ( 16 ) ;
53
+ a1 . run_4 = executionTime ( 8 ) ;
54
+
55
+ console . table ( a1 ) ;
56
+
57
+ console . log ( '\n------------ Bottom Up ------------' ) ;
58
+ const fibBot = fibonacciBottomUp ( ) ;
59
+
60
+ console . log ( 'Term 1:' , fibBot ( 1 ) ) ;
61
+ console . log ( 'Term 6:' , fibBot ( 6 ) ) ;
62
+ console . log ( 'Term 11:' , fibBot ( 11 ) ) ;
63
+ console . log ( 'Term 42:' , fibBot ( 42 ) ) ;
64
+
65
+ // RUN: deno run Algorithms/DynamicProgramming/Fibonacci.ts
66
+ }
67
+
68
+ // --------------------------- Terminal Output: ---------------------------
69
+ //
70
+ // ------------ Memoization ------------
71
+ // Term 256: 8.757159534301882e+52
72
+ // Term 256: 8.757159534301882e+52
73
+ // Term 16: 610
74
+ // Term 8: 13
75
+ // ┌───────┬────────┐
76
+ // │ (idx) │ Values │
77
+ // ├───────┼────────┤
78
+ // │ run_1 │ "2ms" │
79
+ // │ run_2 │ "8ms" │
80
+ // │ run_3 │ "2ms" │
81
+ // │ run_4 │ "12ms" │
82
+ // └───────┴────────┘
83
+ //
84
+ // ------------ Bottom Up ------------
85
+ // Term 1: 0
86
+ // Term 6: 5
87
+ // Term 11: 55
88
+ // Term 42: 165580141
0 commit comments