Created
September 24, 2018 06:11
-
-
Save harrisonmalone/484ad946ec76cc3e8a892dd6e6c955ae to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| require 'pry' | |
| def balanced_num(number) | |
| # my arrays | |
| number_array = number.to_s.chars.map(&:to_i) | |
| lower_array = [] | |
| higher_array = [] | |
| # get the index positions that i need | |
| if number_array.length.odd? | |
| middle_number = number_array.length / 2 | |
| # push values lower than index into lower array and higher values into higher array | |
| number_array.each_with_index do |number, index| | |
| if index < middle_number | |
| lower_array << number | |
| elsif index > middle_number | |
| higher_array << number | |
| else | |
| nil | |
| end | |
| end | |
| #sum the two arrays and return balanced or not balanced | |
| if lower_array.sum == higher_array.sum | |
| answer = "Balanced" | |
| else | |
| answer = "Not Balanced" | |
| end | |
| else | |
| # get the index positions that i need | |
| middle_number_upper = number_array.length / 2 | |
| middle_number_lower = middle_number_upper - 1 | |
| # push values lower than index into lower array and higher values into higher array | |
| number_array.each_with_index do |number, index| | |
| if index < middle_number_lower | |
| lower_array << number | |
| elsif index > middle_number_upper | |
| higher_array << number | |
| else | |
| nil | |
| end | |
| end | |
| #sum the two arrays and return balanced or not balanced | |
| if lower_array.sum == higher_array.sum | |
| answer = "Balanced" | |
| else | |
| answer = "Not Balanced" | |
| end | |
| end | |
| return answer | |
| end | |
| p balanced_num(224222) | |
| # if the array has even length (3547) then there are two middle digits | |
| # if the array has odd length (234) then there is one middle digit | |
| # try to extract the middle digits, then based on its index sum everything below this and above this |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment