Last active
November 25, 2015 15:16
-
-
Save dpaluy/003e7818ecabf8c941da to your computer and use it in GitHub Desktop.
Sorting an Array by Frequency of Appearance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source: Ruby Cookbook https://www.safaribooksonline.com/library/view/ruby-cookbook/0596523696/ch04s09.html