Created
August 27, 2010 20:24
-
-
Save ayb/554131 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ArrayCalculator | |
TEST_ONE = [-7, 1, 5, 2, -4, 3, 0] | |
TEST_TWO = [-7, 1, 5, 2, -4, 3] | |
#= calculate(:at => 3, :arr => [-7, 1, 5, 2, -4, 3, 0]) | |
def self.balanced?(args = {}) | |
raise ArgumentError unless args.has_key?(:at) and args.has_key?(:arr) | |
left_sum, right_sum = 0, 0 | |
(0..(args[:at]-1)).each { |n| left_sum += args[:arr][n] } | |
((args[:at]+1)..(args[:arr].size-1)).each { |n| right_sum += args[:arr][n] } | |
left_sum.eql?(right_sum) | |
end | |
def self.evaluate(arr) | |
k = 0 | |
success = [] | |
while k < arr.size | |
success << k if balanced?(:at => k, :arr => arr) | |
k += 1 | |
end | |
return success | |
end | |
def self.equi(arr) | |
return -1 if arr.empty? or !arr.is_a?(Array) | |
results = evaluate(arr) | |
return -1 if results.empty? | |
return results.size.eql?(1) ? results[0] : results | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment