Created
April 7, 2018 23:13
-
-
Save thdaraujo/17e49d13c4f88a3eeab546dd7d416aa1 to your computer and use it in GitHub Desktop.
Given array of integers, find the lowest absolute sum of elements.
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
def min_abs_sum(a) | |
n = a.size | |
[1, -1].repeated_permutation(n).map do |s| | |
val(a,s).abs | |
end.min | |
end | |
def val(a,s) | |
a.map.with_index{|e, i| a[i] * s[i]}.inject(:+) | |
end | |
solution([1, 5, 2, -2]) | |
# == 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment