0

These two are recursive functions to calculate product sum. First one goes to an infinite loop when the latter works. I don't understand the difference between the two code and the reason why first one doesn't work. Given an array:

[5, 2, [7, -1], 5, [10, [6, 8], 9]

it needs to calculate the sum by this method:

5 * 1 + 2 * 1 + 2*(7 -1 ) + 1 * 5 + 2*(10 + 3*(6 + 8) + 9)

// Tip: You can use the Array.isArray function to check whether an item
// is a list or an integer.
function productSum(array, multiplier = 1) {
  // Write your code here.
  let sum = 0;
  for (i = 0; i < array.length; i++) {
    if (Array.isArray(array[i])) {
      sum += productSum(array[i], multiplier + 1);
    } else {
      sum += array[i];
    }
  }
  return sum * multiplier;
}

// Do not edit the line below.
exports.productSum = productSum;

Above one works but the attempted solution above goes to an infinite loop.

// Tip: You can use the Array.isArray function to check whether an item
// is a list or an integer.
function productSum(array, multiplier = 1) {
  // Write your code here.
  let sum = 0;
  for (const element of array) {
    if (Array.isArray(element)) {
      sum += productSum(element, multiplier + 1);
    } else {
      sum += element;
    }
  }
  return sum * multiplier;
}

// Do not edit the line below.
exports.productSum = productSum;
pilchard
  • 12,414
  • 5
  • 11
  • 23

0 Answers0