Skip to content

Instantly share code, notes, and snippets.

@charleyramm
Last active October 29, 2015 03:10
Show Gist options
  • Save charleyramm/cd6cc59e711c779cc2af to your computer and use it in GitHub Desktop.
Save charleyramm/cd6cc59e711c779cc2af to your computer and use it in GitHub Desktop.
def solution(a)
n = a.size
prefix_sum = [0]
a.each do |e|
prefix_sum << prefix_sum.last + e
end
for i in (0...n) #{}"range excluding n"
left_sum = prefix_sum[i]
right_sum = prefix_sum.last - prefix_sum[i + 1]
if left_sum == right_sum
return i
end
end
-1
end
require 'minitest/autorun'
class TestDemo < Minitest::Test
def test_sample
a = [ -1, 3, -4, 5, 1, -6, 2, 1 ]
assert_equal 1, solution(a)
end
def test_empty
a = []
assert_equal -1, solution(a)
end
def test_no_answer
a = [1, 1]
assert_equal -1, solution(a)
end
def test_left_corner
a = [0, 1, -1]
assert_equal 0, solution(a)
end
def test_right_corner
a = [0, 0]
assert_equal 9, solution(a), "hello"
end
end
@zhifuge
Copy link

zhifuge commented Oct 29, 2015

That's awesome!
Line 24 should be:
class TestDemo < Minitest::Test

@charleyramm
Copy link
Author

That was an unusual autocomplete... I also had a stray n before (0...n)

It works now :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment