Recursion in algorithms…
I’m not sure if I mentioned that I don’t like algorithms in my last blog but I don’t like algorithms. I also never really liked problem solving when I was younger, I hated math. I hated math because I didn’t understand it, I didn’t understand it because I didn’t apply myself. I realize that now that I’m older and went back to school in my 30s and had to take college algebra. This time though I made sure to apply myself and because I made time to understand by not just practicing but also applying myself, immersing myself in it. At the end of the semester I had a B+ in college algebra, I’ve never gotten more than a C in math in my life. So I remind myself when I say that I hate algorithms it’s because I’m thinking about it the same way I did when I was younger. That I’m not smart enough, didn’t spend enough time understanding what and why. I am now though and it’s a marathon not a sprint. I am becoming more comfortable and less afraid of algorithms but there’s so much to learn !
One of the things I struggle with is figuring out how to solve a problem in different ways. It brings me back to the feeling of Mod 1 at Flatiron, where I had to learn Ruby and everything sounded like Charlie Brown’s teacher. The above problem is finding the factorial of number, all the means is multiplying each number leading up to and including the number, and returning the amount, 1*2*3= 6 or 1*2*3*4 = 24. Starting with line 2, my helper variable result needs to equal 1 because we are multiplying and not adding. In the loop, lines 3 & 4, I multiply every number with each other leading up to whatever number is passed in. Note that i is equal to 2 because multiplying 1 * 1 will always be 1 so that’s pointless.
What is Recursion? The process in which a function calls itself directly or indirectly is called and the corresponding function is called as recursive function. Using recursion in an algorithm, certain problems can be solved quite easily. Line 2 is my base case so that I can exit the loop, i.e the condition needed to be met. Why 1? Because once we hit 1, which will happen the function doesn’t need to be called again, instead just returns 1. Line 5 is returning the number entered and calling on the fact function again but this time reducing it by one. So that means if I passed in 3, it’ll skip the loop lines 2 & 3, go directly to line 5, execute 3 x 3–1, number is now 2, then execute the fact function again with 2, number eventually is 1 so result of the stacked functions calls is 6. It was really hard for me to wrap my brain around recursion but this example simplified for me what it does exactly. There’s so much to learn when it comes to programming & I know I will never know everything but my goal to understand these things work & implement them into my coding style. Until next time !