Recurssions Flashcards

1
Q

fibonacci

A

static int fib(int target)
{
if(target <= 1) {
return 1;
}

    return fib(target-1) + fib(target-2);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

sum range

// 5 + 10
// (4 + 6)
// (3 + 3)
// (2 + 1)

A

static int sumRange(int num){
if(num == 1) return 1;
return num + sumRange(num-1);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

factorial

// factorial of 4
// 4 x 3 x 2 x 1 = 24

A

function factorial1(num){
if(num === 1) return 1;
return num * factorial1(num-1);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

find odd values

A

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])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

palindrome

A

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’))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly