def count_between(array, lower_bound, upper_bound) array1 = [] array.each do |x| if x < lower_bound puts nil elsif x > upper_bound puts nil else array1 << x end end return array1.length end
Tuesday, January 22, 2013
count_between exercise
Ok, so it's official. I'm hooked! I wake up at 5:30 because I have a problem of kicking all the sheets off my bed and I see an email about how unnecessarily difficult one of the other students made the count_between problem and I remember that I had a pretty difficult time when I tried it so I wanted to see if I could solve it a new way now that I am starting to get the hang of this. I solved the problem in less than two minutes and I was really proud of how simple it was now that I approached the problem from knowing what I needed to do and then coding it after. I was able to take exactly what was in my head and put it into code. My though process was that I could either take slices off the array or I could create a new array within the boundaries and I thought the latter would be easier. This solution may not have the least lines of code needed to write this, but I think it is elegant, straight forward, and extremely easy to read and understand. So here it is, tell me what you think.
Subscribe to:
Post Comments (Atom)
No need to make an array -- just have a simple integer counter.
ReplyDeletecounter = 0, then in the else put counter += 1. You also don't need to puts nil.
You can condense this a lot further by doing a one-liner:
counter += 1 if x > lower_bound && x < upper_bound
(Might need some parenthesis in there to separate the logic -- not sure).
Interesting. This makes perfect sense! I'll try this later today...
ReplyDelete