Created
May 14, 2012 22:23
-
-
Save peterc/2697817 to your computer and use it in GitHub Desktop.
100% scorer for Ruby on Codility's 'equi' test
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
# http://codility.com/ for info | |
def equi(a) | |
pres, posts = 0, a.reduce(:+) | |
0.upto(a.length - 1) do |pivot| | |
pres += (pivot > 0 ? a[pivot-1] : 0) | |
posts -= a[pivot] | |
return pivot if pres == posts | |
end | |
-1 | |
end | |
#puts equi([-7, 1, 5, 2, -4, 3, 0]) | |
def equi(a)
left, right = 0, a.inject{|sum, k| sum += k}
(0...a.length).each do |j|
# deduct right part
right = right - a[j]
# skip first iterate for left
left = left + a[j-1] if j > 0
return j if left == right
end
-1
end
@mikhailov a.inject{|sum, k| sum += k}
is long form of a.reduce(:+)
or a.reduce(&:+)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cool; thanks! My first attempt got 43% as it failed on a couple of edge cases, and all of the performance tests :-(
Good to learn about the better solution.