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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.