-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursion.ts
More file actions
56 lines (41 loc) · 1.09 KB
/
recursion.ts
File metadata and controls
56 lines (41 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
EXAMPLE 1:
Function that find a factorial of any number:
*/
import chalk from "chalk";
const findFactorial = (n: number): number => {
if (n === 1) return n;
return n * findFactorial(n - 1);
};
console.log(findFactorial(5));
/*
EXAMPLE 1:
Function that returns the value of the Fibonacci sequence being N this index
// 1, 1, 2, 3, 5, 8, 13...
Input: 7
Output: 8
*/
// The recutsive solution has O(2^n), a very bad Time complexity
const fibonacci = (n: number): number => {
if (n < 2) return n;
return fibonacci(n - 2) + fibonacci(n - 1);
};
console.log(chalk.red(fibonacci(7)));
// The Iterative Solution would be O(n):
const fibonacciIter = (n: number): number => {
let arr = [0, 1];
if (n === 0) return 0;
for (let i = 1; i < n; i++) {
arr.push(arr[i - 1] + arr[i]);
}
return arr[arr.length - 1];
};
console.log(chalk.blue(fibonacciIter(7)));
// Reverse a string using recursion
function reverseString(str: string): string {
if (str === "") {
return "";
}
return reverseString(str.substring(1)) + str.charAt(0);
}
console.log(chalk.green(reverseString("reverse")));