-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrecursion.js
More file actions
49 lines (39 loc) · 1.01 KB
/
recursion.js
File metadata and controls
49 lines (39 loc) · 1.01 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
//! basic example
// const goToLunch = (person) => {
// if (person == 5) return true;
// console.log(person);
// return goToLunch(person + 1);
// };
// console.log("outcome", goToLunch(1));
//! convert loop into recursive functions
function multiply(arr) {
let product = 1;
for (let i = 0; i < arr.length; i++) {
product *= arr[i];
}
return product;
}
// console.log(multiply([1, 2, 3, 4]));
function multiply(arr) {
console.log(arr);
if (arr.length <= 0) {
return 1;
} else return arr[arr.length - 1] * multiply(arr.slice(0, arr.length - 1));
}
// console.log(multiply([1, 2, 3, 4]));
//! factorial n=5 -> 5*4*3*2*1
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
// console.log(factorial(5));
//! range of numbers
function rangeOfNumbers(startIndx, endIndx) {
if (startIndx > endIndx) return [];
else {
const numbers = rangeOfNumbers(startIndx, endIndx - 1);
numbers.push(endIndx);
return numbers;
}
}
// console.log(rangeOfNumbers(1, 5));