Skip to content

Instantly share code, notes, and snippets.

@szajbus
Created January 22, 2010 02:23
Show Gist options
  • Save szajbus/283449 to your computer and use it in GitHub Desktop.
Save szajbus/283449 to your computer and use it in GitHub Desktop.
# Finds equilibrium index of a sequence.
# Returns equilibrium index or -1 if no equilibrium exists.
def equi(arr)
left = sums(arr)
right = sums(arr.reverse)
for i in 1..(arr.length) do
return (i-1) if left[i-1] == right[-i]
end
-1
end
def sums(arr)
sums = [0]
arr.each_with_index do |a, i|
sums << sums[i] + a unless i == (arr.length - 1)
end
sums
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment