Home > Software engineering >  Why i can't return value from recursive function?
Why i can't return value from recursive function?

Time:03-18

I am solving the mini-max task on hackerrank.

https://www.hackerrank.com/challenges/mini-max-sum/problem?isFullScreen=true

For that i have the following code where i use recursion until i hit the array length

let arr = [1,2,3,4,5];


let sumsArr = [];
function sumMiniMax(arr, length) {
    let sum = 0;

    for(let i = 0;i < arr.length;i  ) {
        if(i != length) {
            sum  = arr[i];
        }
    }
    sumsArr.push(sum);
    length = length   1;
    if(length == arr.length) {
        let result = findMinAndMax(sumsArr);
        console.log('result local', result);
        return result
    } else {
        sumMiniMax(arr, length)
    }
}

function findMinAndMax(sumsArr) {
    return Math.min(...sumsArr)   '\n'   Math.max(...sumsArr)
}

let res = sumMiniMax(arr, 0);
console.log('res', res);

in the result local i am getting the expected output 10 and 14 but after the recursion is done i want to return the result from findMinAndMax to the original caller which is sumMiniMax

In that case i am getting only undefined but before i return the value we can see that the correct output in the local scope in found 10 and 14. Why is that ?

CodePudding user response:

Not all of your code paths return a value. You need to propagate your result up the call stack. In your case the

return sumMiniMax(arr, length);

is missing in the else branch of your function sumMiniMax().

CodePudding user response:

You could take a single loop approach by having a sum of the three non min and non max values and keep min and max value for adding later.

function getMinMax(array) {
    let min = array[0] < array[1] ? array[0] : array[1],
        max = array[0] > array[1] ? array[0] : array[1],
        sum = 0;

    for (let i = 2; i < array.length; i  ) {
        const value = array[i];
        if (min > value) {
            sum  = min;
            min = value;
            continue;
        }
        if (max < value) {
            sum  = max;
            max = value;
            continue;
        }
        sum  = value;
    }
    return [min   sum, max   sum].join(' ');
}

console.log(getMinMax([1, 2, 3, 4, 5]));

CodePudding user response:

I think recursion in this case is kind of over-engineering. The task has a straightforward approach:

function miniMaxSum(arr) {
    const sumWithout = (el) => {
        const elIndex = arr.indexOf(el);
        const arrWithout = arr.filter((_, i) => i !== elIndex);
        return arrWithout.reduce((sum, num) => sum   num);
    };
    
    const maxEl = Math.max(...arr);
    const minEl = Math.min(...arr);
    
    console.log(sumWithout(maxEl), sumWithout(minEl));
};

miniMaxSum([1,2,3,4,5]);
.as-console-wrapper{min-height: 100%!important; top: 0}

  • Related