Use recursion on array [closed]

Tags: , ,



Write a function that by given array of integers, and a positive number X, returns the product of all odd elements that are greater than X. Use recursion!

I tried this:

function result(arr, x) {
    if (arr.length <= 0) {
        return 0;
    }

    if (arr[0] > x && arr[0] % 2 === 1) {
        return arr[0] + result(arr.slice(1));
    }

    return result(arr.slice(1));
}

console.log(result([3, 2, 3, 4, 5, 6, 7, 8, 9], 1));

And the answer is 3. After the first iteration (x becomes undefined).

Answer

Try like this:

function result(arr, x) {
    if (arr.length <= 0) {
        return 0;
    }

    if (arr[0] > x && arr[0] % 2 === 1) {
        return arr[0] + result(arr.slice(1), x);
    }

    return result(arr.slice(1), x);
}

console.log(result([3, 2, 3, 4, 5, 6, 7, 8, 9], 1));

You were very close! You only needed to pass the value of x into the result function when calling it again. After that, it returns the correct answer: 3 + 3 + 5 + 7 + 9 = 27


EDIT: x needs to be passed into the function call each time because of the scope of the variables. So far, the result function only knows about the variables passed directly into it.

If x is a constant, another way to deal with that would be to define x at the beginning and then change the function to only accept the array:

    const x = 1;

    function result(arr) {
        if (arr.length <= 0) {
            return 0;
        }

        if (arr[0] > x && arr[0] % 2 === 1) {
            return arr[0] + result(arr.slice(1));
        }

        return result(arr.slice(1));
    }

    console.log(result([3, 2, 3, 4, 5, 6, 7, 8, 9]));

If x is not a constant, but you only want to pass the value into a recursive function once, you can do that too with a sub-function, e.g.:

    function result(arr, x) {
      function recur(arr) {
        if (arr.length <= 0) {
          return 0;
        }

        if (arr[0] > x && arr[0] % 2 === 1) {
          return arr[0] + recur(arr.slice(1));
        }

        return recur(arr.slice(1));
      }

      return recur(arr);
    }

    console.log(result([3, 2, 3, 4, 5, 6, 7, 8, 9], 1));

In this case, the recur function can access the variables passed directly into it (arr) as well as the variables of its parent function (x). The value of arr of the closest available scope is used. This method can be helpful in simplifying complicated recursive functions.



Source: stackoverflow