Yet another take on recursion

Recursion is often one of the hardest things to "get" in programming, so when you have your "aha" moment, it's that much more amazing. Conceptually, it's not that hard to see, but how do you actually program one such? 

First, realize that "recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem."

Let us try something simple. Let's say... I want you to sum up the elements of an arbitrary array, let's call it arr. It can have any number of elements, and each element is an integer. For the purpose of this exercise, let's just say it's [1,2,3,4], but it can be any integer, and the array can be any valid size. And I want to you use recursion, not loop (no for or while or such statements). 

Now, remember the definition: "solving a problem where the solution depends on the solutions to smaller instances of the same problem". 

Let's call this function rsum (for recursive sum). So I need you to write:

function rsum(arr) {
// your code goes here
}

So if I call rsum([1,2,3,4]) I should get back 10. 

Now, you know the answer involves calling rsum within rsum. And the trick is it has to stop at one point. 

Let's consider... How do we know the answer? Think about it. At what point, do we know the right answer? Or in other words, what is the "smallest" problem that we can reduce this to? 

The answer is... when we know we just have ONE element in the array. Like [4]. There is nothing to sum, so we just return the item.

So we know the end condition: 

    if (arr.length==1) {
        return arr[0] }

But what about everything else? What is the "smaller" instead of "smallest" problem? 

We know the recursion consists of calling ITSELF. So let's think about it... Given a 4 item array, what's a smaller version of the problem? 

A 3 item array, of course. 

And this works on the 3 item array, which means a 2-item array. 

And a 2 item array can be reduced to a 1-item array... Which we just solved. 

But how do you put all this into code? It's a lot simpler than you think. 

return arr[0]+rsum(arr.slice(1))

You take the first element, then add it to the rsum of 2nd element and on. 

NOTE: Slice(1) of [1,2,3,4] = [2,3,4]. See MDN documentation.   

So this, when executed, becomes...

1 + rsum([2,3,4])

which is

1 + 2 + rsum([3,4])

which is 

1 + 2 + 3 + rsum([4])

which is 

1+2+3+4

which is 10

When you fit together everything, you get this:

function rsum(arr) {
    if (arr.length==1) {
        return arr[0]
    } else {
        return arr[0]+rsum(arr.slice(1))
    }
}

Now that doesn't sound that hard, does it? 

Comments

Popular posts from this blog

Problem Solving for Programmers: a Neglected Topic?

How to Solve a Problem, with Examples