new class js -advanced
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
function factorial(n) {
|
||||
// Base case: if n is 0, return 1
|
||||
if (n === 0) {
|
||||
return 1;
|
||||
}
|
||||
// Recursive case: n * factorial of (n - 1)
|
||||
return n * factorial(n - 1);
|
||||
}
|
||||
|
||||
// Test cases
|
||||
console.log(factorial(5)); // => 120
|
||||
console.log(factorial(3)); // => 6
|
||||
console.log(factorial(0)); // => 1
|
||||
@@ -0,0 +1,23 @@
|
||||
function fibonacci(n) {
|
||||
// Base cases
|
||||
if (n === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (n === 1) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Recursive case
|
||||
return fibonacci(n - 1) + fibonacci(n - 2);
|
||||
}
|
||||
|
||||
// Test cases
|
||||
console.log(fibonacci(0)); // => 0
|
||||
console.log(fibonacci(1)); // => 1
|
||||
console.log(fibonacci(2)); // => 1
|
||||
console.log(fibonacci(3)); // => 2
|
||||
console.log(fibonacci(4)); // => 3
|
||||
console.log(fibonacci(5)); // => 5
|
||||
console.log(fibonacci(6)); // => 8
|
||||
console.log(fibonacci(10)); // => 55
|
||||
@@ -0,0 +1,17 @@
|
||||
function fibonacciMemo(n, memo = {}) {
|
||||
// Base Cases
|
||||
if (n === 0) return 0;
|
||||
if (n === 1) return 1;
|
||||
|
||||
// Test if value already calculated
|
||||
if (memo[n]) {
|
||||
return memo[n];
|
||||
}
|
||||
|
||||
// Recursive Case with Memoization
|
||||
memo[n] = fibonacciMemo(n - 1, memo) + fibonacciMemo(n - 2, memo);
|
||||
return memo[n];
|
||||
}
|
||||
|
||||
// Test Cases
|
||||
console.log(fibonacciMemo(50)); // => 12586269025
|
||||
@@ -0,0 +1,13 @@
|
||||
function sumArray(arr) {
|
||||
// Base case: when the array is empty, return 0
|
||||
if (arr.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
// Recursive case: add the first element to the sum of the rest of the array
|
||||
return arr[0] + sumArray(arr.slice(1));
|
||||
}
|
||||
|
||||
// Test cases
|
||||
console.log(sumArray([1, 2, 3, 4, 5])); // => 15
|
||||
console.log(sumArray([10, -2, 33, 47])); // => 88
|
||||
console.log(sumArray([])); // => 0
|
||||
@@ -0,0 +1,13 @@
|
||||
function sumArrayIndex(arr, index = 0) {
|
||||
// Base case: when index is greater than or equal to the length of the array return 0
|
||||
if (index >= arr.length) {
|
||||
return 0;
|
||||
}
|
||||
// Recursive case: add the current element to the sum of the rest of the array
|
||||
return arr[index] + sumArrayIndex(arr, index + 1);
|
||||
}
|
||||
|
||||
// Test cases
|
||||
console.log(sumArrayIndex([1, 2, 3, 4, 5])); // => 15
|
||||
console.log(sumArrayIndex([10, -2, 33, 47])); // => 88
|
||||
console.log(sumArrayIndex([])); // => 0
|
||||
Reference in New Issue
Block a user