Skip to content

Instantly share code, notes, and snippets.

@sobstel
Created October 25, 2011 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sobstel/1313873 to your computer and use it in GitHub Desktop.
Save sobstel/1313873 to your computer and use it in GitHub Desktop.
Codility demo test (Ruby)
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