Created
June 12, 2014 12:46
-
-
Save sebglazebrook/ce1eec41fe07a02cdd2f to your computer and use it in GitHub Desktop.
Extreme
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
| def average(array) | |
| array.inject(0) { |memo, element| memo += element } / array.size | |
| end | |
| def calculate_deviation(value, average) | |
| value >= 0 ? value - average : average - value | |
| end | |
| def solution(a) | |
| extreme_element_index = -1 | |
| average = average(a) | |
| a.each_with_index.inject(nil) do |highest_deviation, (element, index)| | |
| deviation = calculate_deviation(element, average) | |
| if deviation > average | |
| if extreme_element_index != -1 | |
| if deviation > highest_deviation | |
| highest_deviation = deviation | |
| extreme_element_index = index | |
| end | |
| else | |
| highest_deviation = deviation | |
| extreme_element_index = index | |
| end | |
| end | |
| highest_deviation | |
| end | |
| extreme_element_index | |
| end | |
| a = [9,4,-3,-10] | |
| puts solution(a) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment