Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement