Skip to content

Instantly share code, notes, and snippets.

@thdaraujo
Created April 7, 2018 23:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thdaraujo/17e49d13c4f88a3eeab546dd7d416aa1 to your computer and use it in GitHub Desktop.
Save thdaraujo/17e49d13c4f88a3eeab546dd7d416aa1 to your computer and use it in GitHub Desktop.
Given array of integers, find the lowest absolute sum of elements.
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