3

So I need to solve this problem STRICTLY using recursion

// 2. Compute the sum of an array of integers.
// sum([1,2,3,4,5,6]); // 21

And then I'm testing this solution in PythonLive

var sum = function(array) {
  if(array.length===0){
    return array
    }
  
  return array.slice(0,array.length)+sum(array.pop())

};
sum([1,2,3,4,5,6]);

Then at step 6 it says "TypeError: array.slice is not a function"

I don't understand why if it already worked taking 6 off the array and returning the remaining array...

Can someone explain me what am I doing wrong please?

thanks! :)

1
  • 1
    You have an array of numbers, when you recurse with array.pop() as the argument you're passing a number, not an array. Numbers do not have a slice method. Commented Aug 25, 2018 at 23:04

4 Answers 4

2

If you look at the return values you will see that you are always returning an array. This can't be right when you want a number as a final result. When array.length === 0 you can safely return 0 because that's the same of an empty array. That's your edge condition. After that you just want the sum of one element plus the rest.

You can also just return the array length when it's zero making for a very succinct solution. && shortcircuits returning the left element if it's false (like 0) otherwise the second:

var sum = (array) => array.length && array.pop() + sum(array)

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

If you prefer slice you could also this, which is basically the same:

var sum = (array) => array.length && array[0] + sum(array.slice(1))

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

Sign up to request clarification or add additional context in comments.

1 Comment

Super CRAZY and ELEGANT solutions you Jared and Mark! Thanks! I'm a beginner now but I hope I can reach your level one day! Thanks!
1

Recursive sum function:

const sum = list => {
  if (!list.length) return 0;
  return list.pop() + sum(list);
};

Because .pop mutates the array, you don't need to use slice. For a non-destructive version (doesn't alter the original array):

const sum = ([first, ...rest]) => {
  if (first === undefined) return 0;
  return first + sum(rest);
};

2 Comments

Super CRAZY and ELEGANT solutions you Jared and Mark! Thanks! I'm a beginner now but I hope I can reach your level one day! Thanks!
@Adolf caring about elegance is the first step on the road. Safe travels!
1

The issue with your code is that you are processing the values the wrong way around, it should be

return sum(array.slice(0,array.length-1)) + array.pop();

In fact since array.pop() removes the element, you can just do it this way around:

return array.pop() + sum(array);

You also need to return 0 when array.length===0, otherwise the sum will fail.

if (array.length===0) return 0;

However it's much simpler just do this with reduce:

let arr = [1,2,3,4,5,6];
console.log(arr.reduce((t, v) => { return t + v; }, 0));

3 Comments

Good recommendations, except your solution, return array.pop() + sum(array); is returning strings
Thanks for your answers! Ur right in the pop method actually! :) the problem with that its that its actually returning not a result of a sum but ANOTHER array with the same number either backwards or regular BUT all along together, not as separated elements. I need the answer to be 21... :(
I've edited (again!) to include the fact that you must return 0 when the array is empty, not array
0

Another encoding using an explicit empty and pure expressions

const empty = x =>
  x === empty
  
const sum = ([ x = empty, ...rest ]) =>
  empty (x)
    ? 0
    : x + sum (rest)
    
console.log
  ( sum ([ 1, 2, 3, 4, 5 ]) // 15
  , sum ([])                // 0
  )

Your other question that asks how to sum a nested array was put on-hold for reasons I don't understand. You can adapt the above implementation to support input of nested arrays

const empty = x =>
  x === empty
  
const sum = ([ x = empty, ...rest ]) =>
  empty (x)
    ? 0
    
  : Array.isArray (x)
    ? sum (x) + sum (rest)
  
  : x + sum (rest)
    
console.log
  ( sum ([ 1, [ 2, [ 3, 4 ], 5 ]]) // 15
  , sum ([ 1, 2, 3, 4, 5 ])        // 15
  , sum ([[[]]])                   // 0
  , sum ([])                       // 0
  )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.