Recipe 4.9. Sorting an Array by Frequency of AppearanceProblemYou want to sort an array so that its least-frequently-appearing items come first. SolutionBuild a histogram of the frequencies of the objects in the array, then use it as a lookup table in conjunction with the sort_ The following method puts the least frequently-appearing objects first. Objects that have the same frequency are sorted normally, with the comparison operator.
DiscussionThe sort_by_frequency method uses sort_by, a method introduced in Recipe 4.5 and described in detail in Recipe 4.6. The technique here is a little different from other uses of sort_by, because it sorts by two different criteria. We want to first compare the relative frequencies of two items. If the relative frequencies are equal, we want to compare the items themselves. That way, all the instances of a given item will show up together in the sorted list. The block you pass to Enumerable#sort_by can return only a single sort key for each object, but that sort key can be an array. Ruby compares two arrays by comparing their corresponding
In our case, all the arrays contain two elements: the relative frequency of an object in the array, and the object itself. If two objects have different frequencies, the first elements of their arrays will differ, and the items will be sorted based on their frequencies. If two items have the same frequency, the first element of each array will be the same. The comparison method will move on to the second array element, which means the two objects will be sorted based on their values. If you don't mind
To sort the list so that the most-frequently-appearing items show up first, either invert the result of sort_by_frequency, or multiply the histogram values by1 when passing them into sort_by:
If you want to sort a list by the frequency of its elements, but not have repeated elements actually show up in the sorted list, you can run the list through Array#uniq after
See Also
|
Thursday, October 29, 2009
Recipe 4.9. Sorting an Array by Frequency of Appearance
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment