Codility demo test (Ruby)
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 equi(a) | |
lower_elements_sum = 0 | |
higher_elements_sum = a.inject(:+) | |
a.each_with_index do |el, i| | |
lower_elements_sum += a[i - 1] if i > 0 | |
higher_elements_sum -= el | |
return i if lower_elements_sum == higher_elements_sum | |
end | |
return -1 | |
end | |
describe "equi" do | |
it "returns equilibrium index" do | |
equi([-7, 1, 5, 2, -4, 3, 0]).should satisfy { |n| [3,6].include?(n) } | |
equi([3, 2, 1, -6, 0]).should eql(4) | |
equi([0, 3, 2, 1, -6]).should eql(0) | |
end | |
it "returns -1 if no equilibrium index exists" do | |
equi([1, 2, 3, 4, 5, 6]).should eql(-1) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment