Skip to content

Commit 768b6a2

Browse files
Implemented dynamic programming (Closes CoffeelessProgrammer#12)
1 parent a5fa14a commit 768b6a2

File tree

6 files changed

+196
-12
lines changed

6 files changed

+196
-12
lines changed
+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// ----------------------- Class Implementation -----------------------
2+
class MemoizationExample {
3+
private static cache = Object.create({});
4+
5+
public static resetCache() {
6+
this.cache = null;
7+
this.cache = Object.create({});
8+
}
9+
10+
public static memoizedAddTo42(n: number, visualize?: boolean): number {
11+
if (n in this.cache) {
12+
if (visualize) console.log('Found!', n, '+ 42 =', this.cache[n]);
13+
return this.cache[n];
14+
} else {
15+
if (visualize) console.log('New encounter!', n);
16+
this.cache[n] = n + 42;
17+
return this.cache[n]
18+
}
19+
}
20+
21+
public static addTo42(n: number): number {
22+
console.log('Long time!', n);
23+
return n + 42;
24+
}
25+
}
26+
27+
// ----------------------- Closure Implementation -----------------------
28+
function memoizedAddTo64() {
29+
let cache = Object.create({});
30+
31+
return function(n: number): number {
32+
if (n in cache) {
33+
console.log('Found!', n, '+ 64 =', cache[n]);
34+
return cache[n];
35+
} else {
36+
console.log('New encounter!', n);
37+
cache[n] = n + 64;
38+
return cache[n]
39+
}
40+
}
41+
}
42+
43+
//---------------------------------------------------------------------
44+
// ---------- MAIN PROGRAM ----------
45+
//---------------------------------------------------------------------
46+
if (import.meta.main) {
47+
48+
console.log('------------ Memoization via Class ------------');
49+
MemoizationExample.memoizedAddTo42(17, true);
50+
MemoizationExample.memoizedAddTo42(15, true);
51+
MemoizationExample.memoizedAddTo42(17, true);
52+
MemoizationExample.memoizedAddTo42(28, true);
53+
MemoizationExample.memoizedAddTo42(28, true);
54+
55+
console.log('\n----------- Memoization via Closure -----------');
56+
const memoized = memoizedAddTo64();
57+
58+
memoized(7);
59+
memoized(5);
60+
memoized(5);
61+
62+
// RUN: deno run Algorithms/DynamicProgramming/Basics.ts
63+
}
64+
65+
// --------------------------- Terminal Output: ---------------------------
66+
// ------------ Memoization via Class ------------
67+
// New encounter! 17
68+
// New encounter! 15
69+
// Found! 17 + 42 = 59
70+
// New encounter! 28
71+
// Found! 28 + 42 = 70
72+
73+
// ----------- Memoization via Closure -----------
74+
// New encounter! 7
75+
// New encounter! 5
76+
// Found! 5 + 64 = 69
+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
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

Algorithms/README.md

+12-9
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
## Core
44
- [X] Recursion
5-
- [ ] Dynamic Programming
5+
- [X] Dynamic Programming
66
- [X] Comparison Sorting
77
- [X] *Merge Sort*
88
- [X] *Quicksort*
@@ -20,17 +20,24 @@
2020
- [Unicode Characters | RapidTables](https://www.rapidtables.com/code/text/unicode-characters.html)
2121
- [The Big-O Algorithm Complexity Cheat Sheet](https://www.bigocheatsheet.com/ "Big O Cheat Sheet")
2222

23+
### Dynamic Programming
24+
- [Closures | JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)
25+
26+
### Recursion
27+
- [Recursion | Brilliant.org](https://brilliant.org/wiki/recursion-problem-solving/)
28+
- [Tail Call Optimization in ES6](https://2ality.com/2015/06/tail-call-optimization.html)
29+
2330
### Searching
24-
- [Graph Traversals: VisuAlgo](https://visualgo.net/en/dfsbfs)
31+
- [Graph Traversals | VisuAlgo](https://visualgo.net/en/dfsbfs)
2532
- [Tree Traversals: Preorder, Inorder, & Postorder](https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/)
2633
- [Space Complexity: BFS vs DFS](https://stackoverflow.com/questions/9844193/what-is-the-time-and-space-complexity-of-a-breadth-first-and-depth-first-tree-tr)
2734

2835
### Sorting
2936
- [Array.prototype.sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
3037
- [Animated Sorting | Toptal](https://www.toptal.com/developers/sorting-algorithms)
31-
- [Dancing Algorithms | AlgoRythmics](https://www.youtube.com/user/AlgoRythmics/videos)what-is-stability-in-sorting-algorithms-and-why-is-it-important)
38+
- [Dancing Algorithms | AlgoRythmics](https://www.youtube.com/user/AlgoRythmics/videos)
3239
- [QuickSort vs Heapsort](https://stackoverflow.com/questions/2467751/quicksort-vs-heapsort)
33-
- [Importance of Stability in Sorting](https://stackoverflow.com/questions/1517793/)
40+
- [Importance of Stability in Sorting](https://stackoverflow.com/questions/1517793/what-is-stability-in-sorting-algorithms-and-why-is-it-important)
3441

3542
### Most Common Sorts
3643
- [Merge Sort | Brilliant.org](https://brilliant.org/wiki/merge/)
@@ -39,8 +46,4 @@
3946
- [Radix Sort | Brilliant.org](https://brilliant.org/wiki/radix-sort/ "Non-Comparison Sort")
4047
- [Radix Sort Visualization](https://www.cs.usfca.edu/~galles/visualization/RadixSort.html)
4148
- [Counting Sort | Brilliant.org](https://brilliant.org/wiki/counting-sort/ "Non-Comparison Sort")
42-
- [Counting Sort Visualization](https://www.cs.usfca.edu/~galles/visualization/CountingSort.html)
43-
44-
### Recursion
45-
- [Recursion | Brilliant.org](https://brilliant.org/wiki/recursion-problem-solving/)
46-
- [Tail Call Optimization in ES6](https://2ality.com/2015/06/tail-call-optimization.html)
49+
- [Counting Sort Visualization](https://www.cs.usfca.edu/~galles/visualization/CountingSort.html)

Algorithms/Recursion/Fibonacci.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,9 @@ if (import.meta.main) {
9393
// Fibonacci Iterative 5: 3
9494
// Fibonacci Iterative 6: 5
9595
// Fibonacci Iterative 9: 21
96+
// Fibonacci Iterative 42: 165580141
97+
// Fibonacci Iterative 50: 7778742049
98+
// Fibonacci Iterative 100: 218922995834555200000
9699

97100
// ------------ Recursive ------------
98101
// Input -1 is invalid -_-'
@@ -103,4 +106,5 @@ if (import.meta.main) {
103106
// Fibonacci Recursive 4: 2
104107
// Fibonacci Recursive 5: 3
105108
// Fibonacci Recursive 7: 8
106-
// Fibonacci Recursive 8: 13
109+
// Fibonacci Recursive 8: 13
110+
// Fibonacci Recursive 42: 165580141

Algorithms/Searching/DepthFirstTraversals.ts

+13-1
Original file line numberDiff line numberDiff line change
@@ -92,4 +92,16 @@ if (import.meta.main) {
9292
// RUN: deno run Algorithms/Searching/DepthFirstTraversals.ts
9393
}
9494

95-
// --------------------------- Terminal Output: ---------------------------
95+
// --------------------------- Terminal Output: ---------------------------
96+
// Inorder: [
97+
// 1, 4, 6, 9,
98+
// 15, 20, 170
99+
// ]
100+
// Preorder: [
101+
// 9, 4, 1, 6,
102+
// 20, 15, 170
103+
// ]
104+
// Postorder: [
105+
// 1, 6, 4, 15,
106+
// 170, 20, 9
107+
// ]

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
### Algorithms
2020
- [X] Recursion
21-
- [ ] Dynamic Programming
21+
- [X] Dynamic Programming
2222
- [X] Comparison Sorting
2323
- [X] *Merge Sort*
2424
- [X] *Quicksort*
@@ -36,6 +36,7 @@
3636
- [Comprehensive List of Data Structures](https://en.wikipedia.org/wiki/List_of_data_structures "Wikipedia: DS List")
3737
- [Visualizing Data Structures & Algorithms](https://visualgo.net/en)
3838
- [The Big-O Algorithm Complexity Cheat Sheet](https://www.bigocheatsheet.com/ "Big O Cheat Sheet")
39+
- [Google Coding Interview](https://youtu.be/XKu_SEDAykw)
3940
- [Roadmap: Core Data Structures & Algorithms](https://coggle.it/diagram/W5E5tqYlrXvFJPsq/t/master-the-interview-click-here-for-course-link "Course and Mindmap by Andrei Neagoie")
4041

4142
### Curated Articles

0 commit comments

Comments
 (0)