Created
December 8, 2021 00:08
-
-
Save sarahzrf/01c967a072bb0697eb6c97c6fc50b8b0 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 Integer | |
def sumtorial | |
(0..self).sum | |
end | |
end | |
def cost(counts, x0) | |
counts.sum {|x, n| (x0 - x).abs.sumtorial * n} | |
end | |
count_by_pos = Hash.new(0) | |
gets.chomp.split(',').map(&:to_i).each do |x| | |
count_by_pos[x] += 1 | |
end | |
rg = count_by_pos.keys.min..count_by_pos.keys.max | |
optimal = rg.map {|x| cost(count_by_pos, x)}.min | |
print optimal | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment