Skip to content

Instantly share code, notes, and snippets.

@peterc
Created May 14, 2012 22:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save peterc/2697817 to your computer and use it in GitHub Desktop.
Save peterc/2697817 to your computer and use it in GitHub Desktop.
100% scorer for Ruby on Codility's 'equi' test
# 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])
@prakashmurthy
Copy link

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.

@mikhailov
Copy link

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

@jasonm23
Copy link

@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