Skip to content

Instantly share code, notes, and snippets.

@ashmckenzie
Created December 13, 2010 00:39
Show Gist options
  • Save ashmckenzie/738504 to your computer and use it in GitHub Desktop.
Save ashmckenzie/738504 to your computer and use it in GitHub Desktop.
Equilibrium index code
require 'rubygems'
require 'test/unit'
def equi(list)
left = 0
right = list.inject { |x, y| x + y }
equilibrium_indicies = []
list.each_with_index do |val, i|
right -= val
equilibrium_indicies << i if right == left
left += val
end
unless equilibrium_indicies.empty?
equilibrium_indicies
else
-1
end
end
class TestEqui < Test::Unit::TestCase
def test_one
# should pass
arr = [ -7, 1, 5, 2, -4, 3, 0 ]
assert_equal(equi(arr), [ 3, 6 ])
end
def test_two
# should pass
arr = [ 1, 2, 3, 6, -100, 100, 6 ]
assert_equal(equi(arr), [ 3 ])
end
def test_three
# should pass
arr = [ 1, 2, 3, -100, 103 ]
assert_equal(equi(arr), [ 2 ])
end
def test_four
# should fail
arr = [ 1, 2, 3, -100, 101 ]
assert_equal(equi(arr), -1)
end
def test_start_one
# should succeed
arr = [ 0 ]
assert_equal(equi(arr), [ 0 ])
end
def test_start_two
# should succeed
arr = [ 0, 0 ]
assert_equal(equi(arr), [ 0, 1 ])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment