I spent a bit of time today tackling the equilibrium index problem (described here)
After writing my own solution (which performed badly with large numbers), I decided to find one that would be a perfect score. I found this (which Codility scores as 100/100):
def equi(a)
left, right = 0, a.inject(0, &:+)
indices = []
a.each_with_index do |val, i|
right -= val
indices << i if right == left
left += val
end
indices
end
What I don't understand is the piece of parallel assignment and use of inject at the top of the method. Is anyone able to describe what this is doing?
Many thanks! Stu
It assigns 0 to
leftand the sum ofa's elements toright. The 0 argument is there because otherwise an empty array would returnnil. The shorthand used for summing is Symbol#to_proc and is unnecessary becauseinjectdirectly takes a symbol as its argument -inject(0, :+).