Skip to content

Instantly share code, notes, and snippets.

@adamloo85
Last active December 28, 2015 17:49
Show Gist options
  • Save adamloo85/7538933 to your computer and use it in GitHub Desktop.
Save adamloo85/7538933 to your computer and use it in GitHub Desktop.
README Run by typing "ruby (filename)". Drive code is already included. This script adds a method "find_pivot" to the array class which finds the pivot point of any array and returns the index of that point if it exists or -1 otherwise.
#README
#Run by typing "ruby (filename)". Drive code is already included.
#This script adds a method "find_pivot" to the array class which finds the pivot point of any array
#and returns the index of that point if it exists or -1 otherwise.
class Array
def find_pivot
raise NoMethodError, 'Wrong type of input!' if self.class != Array
low = 0
high = self.length - 1
mid = (low + high) / 2
searches = 0
until searches == (self.length / 2)
searches += 1
left_sum = self[low..mid - 1].inject {|sum, i| sum + i}
right_sum = self[mid + 1..high].inject{|sum, i| sum + i}
if left_sum == right_sum
return mid
elsif right_sum > left_sum
mid += 1
elsif left_sum > right_sum
mid -= 1
end
end
return -1
end
end
p "[1,4,6,3,2].find_pivot yields " + "#{[1,4,6,3,2].find_pivot}."
p "[1,4,6,7,3,2].find_pivot yields " + "#{[1,4,6,7,3,2].find_pivot}."
require_relative 'pivot.rb'
require "test/unit"
class FindPivot < Test::Unit::TestCase
def test_structure
assert_equal Fixnum, [1,2,3,4,5].find_pivot.class
assert_raise NoMethodError do
"adam".find_pivot
end
end
def test_logic
assert_equal 2, [1,4,6,3,2].find_pivot
assert_equal -1, [1,4,6,7,3,2].find_pivot
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment