Skip to content

Instantly share code, notes, and snippets.

@scottchiang
Last active December 19, 2015 13:39
Show Gist options
  • Save scottchiang/5963769 to your computer and use it in GitHub Desktop.
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…
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
@slavingia
Copy link

hi

this is not done in a very efficient way.

@scottchiang
Copy link
Author

refactored the method

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment