Advertisement
Guest User

Untitled

a guest
Nov 25th, 2015
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.69 KB | None | 0 0
  1. module Enumerable
  2. def to_histogram
  3. inject(Hash.new(0)) { | h, x | h[x] += 1; h }
  4. end
  5.  
  6. def sort_by_frequency
  7. histogram = inject(Hash.new(0)) { | hash, x | hash[x] += 1; hash }
  8. sort_by { | x | [histogram[x], x] }
  9. end
  10.  
  11. def sort_by_frequency_faster
  12. histogram = inject(Hash.new(0)) { | hash, x | hash[x] += 1; hash }
  13. sort_by { | x | histogram[x] }
  14. end
  15.  
  16. def sort_by_frequency_descending
  17. histogram = inject(Hash.new(0)) { | hash, x | hash[x] += 1; hash }
  18. sort_by { | x | [histogram[x] * -1, x] }
  19. end
  20.  
  21. def sort_distinct_by_frequency
  22. histogram = inject(Hash.new(0)) { | hash, x | hash[x] += 1; hash }
  23. histogram.keys.sort_by { | x | [histogram[x], x] }
  24. end
  25. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement