Skip to content

Instantly share code, notes, and snippets.

@dpaluy
Last active November 25, 2015 15:16
Show Gist options
  • Select an option

  • Save dpaluy/003e7818ecabf8c941da to your computer and use it in GitHub Desktop.

Select an option

Save dpaluy/003e7818ecabf8c941da to your computer and use it in GitHub Desktop.
Sorting an Array by Frequency of Appearance
module Enumerable
def to_histogram
inject(Hash.new(0)) { | h, x | h[x] += 1; h }
end
def sort_by_frequency
histogram = inject(Hash.new(0)) { | hash, x | hash[x] += 1; hash }
sort_by { | x | [histogram[x], x] }
end
def sort_by_frequency_faster
histogram = inject(Hash.new(0)) { | hash, x | hash[x] += 1; hash }
sort_by { | x | histogram[x] }
end
def sort_by_frequency_descending
histogram = inject(Hash.new(0)) { | hash, x | hash[x] += 1; hash }
sort_by { | x | [histogram[x] * -1, x] }
end
def sort_distinct_by_frequency
histogram = inject(Hash.new(0)) { | hash, x | hash[x] += 1; hash }
histogram.keys.sort_by { | x | [histogram[x], x] }
end
end
@dpaluy
Copy link
Author

dpaluy commented Nov 25, 2015

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