Skip to content

Instantly share code, notes, and snippets.

@cheeyeo
Created May 15, 2014 20:45
Show Gist options
  • Save cheeyeo/5b730317822e04ec350f to your computer and use it in GitHub Desktop.
Save cheeyeo/5b730317822e04ec350f to your computer and use it in GitHub Desktop.
Array equi in ruby
def equi(arr)
return 0 if arr.empty?
left, right = 0, arr.inject{|sum, n| sum + n}
equi_indices=[]
arr.each_with_index do |val,i|
left += val
equi_indices << i if right == left
right -= val
end
return -1 if equi_indices.empty?
equi_indices
end
indices = [
[-7, 1, 5, 2,-4, 3, 0],
[2, 4, 6],
[2, 9, 2],
[1,-1, 1,-1, 1,-1, 1],
[]
]
indices.each do |x|
puts "%p => %p" % [x, equi(x)]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment