Skip to content

Instantly share code, notes, and snippets.

@voleinikov
Created January 18, 2013 09:23
Show Gist options
  • Save voleinikov/4563393 to your computer and use it in GitHub Desktop.
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.
# 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