Last active
December 19, 2015 13:39
-
-
Save scottchiang/5963769 to your computer and use it in GitHub Desktop.
Write a method that returns the "pivot" index of a list. We define the pivot index as the index where the sum of the numbers on the left is equal to the sum of the numbers on the right. For instance given [1, 4, 6, 3, 2], the method should return 2, since the sum of the numbers to the left of index 2 is equal to the sum of numbers to the right o…
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 pivot_index(ary) | |
idx = -1 | |
left_sum = 0 | |
right_sum = ary[1..-1].inject(:+) | |
#can't find pivot if array's length is less than 3 | |
if ary.length > 2 | |
#ignore the first and last element because they only have 1 neighbor | |
1.upto(ary.length - 2) do |x| | |
left_sum += ary[x-1] | |
right_sum -= ary[x] | |
if left_sum == right_sum | |
idx = x | |
break | |
end | |
end | |
end | |
idx | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi
this is not done in a very efficient way.