Recurssions Flashcards
fibonacci
static int fib(int target)
{
if(target <= 1) {
return 1;
}
return fib(target-1) + fib(target-2); }
sum range
// 5 + 10
// (4 + 6)
// (3 + 3)
// (2 + 1)
static int sumRange(int num){
if(num == 1) return 1;
return num + sumRange(num-1);
}
factorial
// factorial of 4
// 4 x 3 x 2 x 1 = 24
function factorial1(num){
if(num === 1) return 1;
return num * factorial1(num-1);
}
find odd values
function collectOddValues(arr){
let result = []; function helper(helperInput){ if(helperInput.length === 0) { return; } if(helperInput[0] % 2 !== 0){ result.push(helperInput[0]) } helper(helperInput.slice(1)) } helper(arr) return result; }
collectOddValues([1,2,3,4,5,6,7,8,9])
answer b:
function collectOddValues(arr){
let newArr = [];
if(arr.length === 0) { return newArr; } if(arr[0] % 2 !== 0){ newArr.push(arr[0]); } newArr = newArr.concat(collectOddValues(arr.slice(1))); return newArr; }
collectOddValues([1,2,3,4,5])
palindrome
const palindrome = (str) => {
const len = str.length - 1
if (str.length === 0) {
return false
}
const helper = (s, e) => { if(str[s] !== str[e]) { return false } if(s < e + 1) { return helper(s + 1, e - 1) } return true } return helper(0, len) }
console.log(palindrome(‘aaaaddd’))