Created
January 18, 2013 09:23
-
-
Save voleinikov/4563393 to your computer and use it in GitHub Desktop.
The x2 "count.times do" followed by the next is my new favorite way to traverse arrays at two different spots.
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
# Array = [1,2,-2,1,0], return array of arrays of pairs of indicies of the values that add up to zero | |
def pairs(array) | |
pairs = [] | |
traverse = array.count | |
traverse.times do |i| | |
traverse.times do |j| | |
# We don't want to check cases where the j value is behind the i value or at the same position | |
# Because we don't want to re-check past values or check the same value | |
# Next helps us do that | |
next if j <= i | |
pairs << [i, j] if array[i] + array[j] == 0 | |
end | |
end | |
pairs | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment