Skip to content

Instantly share code, notes, and snippets.

@budnik
Created November 19, 2017 15:20
Show Gist options
  • Save budnik/39a39abd77a6faa95ba05b04933272d6 to your computer and use it in GitHub Desktop.
Save budnik/39a39abd77a6faa95ba05b04933272d6 to your computer and use it in GitHub Desktop.
Crossover chalange sort
def rearrange(elements)
number_of_ones = Hash.new {|h, n| h[n] = n.to_s(2).each_char.count('1')}
elements.map(&:to_i).uniq.sort do |a,b|
noo_a = number_of_ones[a]
noo_b = number_of_ones[b]
if noo_a==noo_b
a<=>b
else
noo_a<=>noo_b
end
end
end
@budnik
Copy link
Author

budnik commented Nov 19, 2017

Originally second line was like:

number_of_ones = ->(n){n.to_s(2).each_char.count('1')}

but I had lot of spare time so I've added cashing in hash

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment