Skip to content

Instantly share code, notes, and snippets.

@aenain
Last active December 15, 2015 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aenain/5332722 to your computer and use it in GitHub Desktop.
Save aenain/5332722 to your computer and use it in GitHub Desktop.
Equilibrium.
# uses ruby 2.0
require 'test/unit'
module Symmetry
refine Array do
# Returns index of the first equilibrium if found or nil otherwise.
# Equilibrium is a symmetry point of an array - sum of elements before given element equals to a sum of the elements after it.
#
# Caution!
# First element is considered as an equilibrium if sum of the other elements equals 0, same with a last element.
# This method modifies receiver!
#
# Example:
# [10, 20, 100, 30].equilibrium # => 2 (10 + 20 = 30)
# [100, 10, 20, -30].equilibrium # => 0 (0 = 10 + 20 - 30)
# [10, 20, -30, 100].equilibrium # => 3 (10 + 20 - 30 = 0)
# [10, 20, 30].equilibrium # => nil
def equilibrium
prev_sum = 0
# sum previous elements from the end
(count - 2).downto(0) { |i| self[i] += self[i+1] }
# subtract sum of previous elements from the start and return if sums are equal (it's an equilibrium)
each_with_index do |next_sum, index|
number =
if index + 1 < count
next_sum - self[index + 1]
else
next_sum
end
prev_sum += number
return index if next_sum == prev_sum
end
nil
end
end
end
using Symmetry
class EquiTest < Test::Unit::TestCase
def test_first_element
numbers = [1000, 1, 0, -1]
assert_equal 0, numbers.equilibrium
end
def test_last_element
numbers = [-1, 0, 1, 1000]
assert_equal 3, numbers.equilibrium
end
def test_element_inside
numbers = [1, 2, 1000, 3]
assert_equal 2, numbers.equilibrium
end
def test_no_equilibrium
numbers = [1, 2, 3]
assert_nil numbers.equilibrium
end
def test_return_only_first_result
numbers = [1, -1, 0, 1, -1]
assert_equal 2, numbers.equilibrium
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment