Agreed. Though the use of the ST wasn't to reduce the cost of sorting, just a mechanism of grouping the key/value pairs, so that I could sort the values and retain the associating with the respective key.
A linear search is all that is needed. That said, petruchio gave an alternative in the CB which I had to look at several times to understand, but which I think is particularly neat.
my @n; $n[$_{$_}] = $_ for map{$_{$_}++; $_} @list; print "Most frequent: $n[-1]";
I hope he'll forgive me for pushing this one step further with this sub which I have added to my personal utilities module.
sub most_frequent{ local *_=*_; $_[$_{$_}] = $_ for map{$_{$_}++; $_} +@_; $_[-1]; }
Which goes along way to providing, and could easliy be extended to provide most if not all of the function available in the Statistics::Frequency module I saw mentioned, without the overhead of the 50 or so lines of inefficient and frankly rather pedestrian code that make it up.
I find it incredulous that the author implemented a complete function and a nested loop to determine the "sum of the frequencies", which unless I am just too tired, amounts to the size of the list or array?
Just goes to show that you have to read the source before blythly accepting the merit of any given module. Just being a part of CPAN isn't of itself enough to ensure any sort of quality.
Examine what is said, not who speaks.
The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.
In reply to Re: •Re: Most frequent element in an array.
by BrowserUk
in thread Most frequent element in an array.
by BrowserUk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |