Created
January 8, 2010 21:05
-
-
Save samstokes/272412 to your computer and use it in GitHub Desktop.
Solution to Codility demo problem, finding equilibrium index of an array
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
def sums_before(src) | |
dest = [0] | |
src.each_with_index do |item, index| | |
dest[index + 1] = dest[index] + item | |
end | |
dest | |
end | |
def equi ( arr ) | |
sums_left = sums_before(arr) | |
# p sums_left | |
arr.reverse! | |
sums_right = sums_before(arr); sums_right.reverse! | |
# p sums_right | |
arr.each_with_index do |item, index| | |
if sums_left[index] == sums_right[index + 1] | |
return index | |
end | |
end | |
return -1 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment