Skip to content

Instantly share code, notes, and snippets.

@sarahzrf
Created December 7, 2021 23:58
Show Gist options
  • Save sarahzrf/5580d3a1c0809ea12336b8daede787b0 to your computer and use it in GitHub Desktop.
Save sarahzrf/5580d3a1c0809ea12336b8daede787b0 to your computer and use it in GitHub Desktop.
def cost(counts, x0)
counts.sum {|x, n| (x0 - x).abs * 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