Chapter 2: Splitting Bars
In step, we saw how we could use recursive functions to methodically shrink the problem until it was gone. This approach is useful for basic problems like step, but we're going to get more advanced...
Last updated
In step, we saw how we could use recursive functions to methodically shrink the problem until it was gone. This approach is useful for basic problems like step, but we're going to get more advanced...
Last updated
Imagine a bar of solid gold.
You want to find out how much it weighs, but you're held back by one thing:
You only know that a square of gold weighs 5 pounds.
Your gold bar is larger than a square.
As we did before, let's go ahead and define a function. The function split has one parameter: gold_bar, the bar of gold.
split aims to return how many pounds the gold bar weighs.
If our problem is weighing the gold bar, let's think about how we can make the problem smaller! True to the function's name, why don't we try splitting the gold bar...
In this case, we can split the gold bar into:
The square of gold is a known quantity: we know it weighs 5 pounds. The rest of the bar is an unsolved problem. However, it's smaller than our original problem! It's important to realize that when added together, these two smaller problems are equivalent to our original problem, but they're easier for us to solve.
We can take the rest of the bar and split it again, and repeat this process. What does this look like in code?
We keep splitting the rest of the bar in order to make our problem smaller.
Again, because we are making the problem smaller and smaller; this line is the recursive call.
For now, let's continue splitting.
And split the rest of the bar again....
We are left with
but the rest of the bar is a square! That's a known quantity! This is equivalent to
Which is 5 + 5 + 5 + 5 = 20 pounds!
By now you should have realized that our base case is when we have split the gold bar enough times so that it is a square, a known quantity. In code:
Now, every time we split, we see if the gold_bar we're splitting is a square; if it is, we return it, and we're finished! Otherwise, we return square of gold + split(rest of bar), knowing that split will make our problem smaller.
If you're still confused or not completely sold, here's a quick recap to show you what's happening:
So, what was the point of this example? The goal of this example was to introduce the idea of splitting a problem into two smaller ones; In our example, we split the problem of weighing a gold bar into the problems of:
Weighing a square of gold
Weighing the rest of the bar
The first problem we could solve easily, and the second could be split further. In order to generalize this kind of thinking, consider this splitting strategy as splitting a problem into:
A solved or easily solvable problem
A problem that can be further split
I'll give concrete examples in the next chapter, to show you how we can use this approach in real code.