Last active
December 20, 2015 11:39
-
-
Save mecampbellsoup/6125506 to your computer and use it in GitHub Desktop.
better way to effectively iterate one array over another: http://www.ruby-doc.org/core-2.0/Array.html#method-i-26
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sum_of_intersection?(x1, x2, y1, y2) | |
intersection = (x1..x2).to_a & (y1..y2).to_a | |
intersection.inject{|sum,i| sum + i} | |
end | |
p sum_of_intersection?(5,15,10,20) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pretty cool Matt! Love the set intersection operator. One disadvantage to this approach vs how we talked about earlier (where we manually found the intersecting range) is that if one of our ranges were say a billion numbers wide or more, this code would take up a ton of memory due to having to convert the entire range into an array. You can never run out of cool Ruby shortcuts :)