In the beginning.
Well, here we are on the third day of MakerSquare. Cohort 9, of which I am a proud member, started on Tuesday of this week and we hit the ground running! It’s certainly not easy- not that I was expecting it to be- but I’m learning lots of great stuff thanks to our instructors. Nick, Patrick, and Flip are doing a great job.
Today Patrick gave an Intro to Algorithms lecture that was pretty interesting! We talked about the internal mechanics of data structures (really we talked about how Arrays work, at least in Ruby), and then had a series of exercises where we had to create methods to perform certain tasks.
One of the tricks I picked up today that REALLY helped was the “for” loop in Ruby. The method we were to write was to take an array of numbers and see if any two items, when added together, would give us a sum of 0. I struggled with this one until learning about the “for” loop (and even then it took me a little while to wrap my mind around it). The answer to the problem was to string two “for” loops together (in Exponential Time, since we were talking about algorithms). The answer looked something like this:
def self.find_sum_2(array, sum = 0) for i in 0…array.length for j in i…array.length if array[i] + array[j] == sum return true end end end
(if only I could get the formatting right! I’ll have to look in to that for later posts!)
So what’s happening here? The first “for” loop is considering any item “i” which might occur in the range of 0 up to (but not including) the total length of the array “array” (so basically, any index in that array). Within the first “for” loop, the second “for” loop considers any item “j” (much like the first loop) that is any index in the array. The conditional statement immediately following checks to see is any item in array, when added to any other item in the same array, will give us our desired sum.
I’m not sure if I’m describing that adequately, but regardless it makes sense to me! It was a great feeling when the switch finally flipping inside my brain, and the exercises we were doing suddenly made much more sense.
I’ve got another powerful tool in my belt, and I can’t wait to see what other tricks I learn!
Email me when Bradley Anderson publishes or recommends stories