Created
January 22, 2010 02:23
-
-
Save szajbus/283449 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# 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