CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Finding the most common value

 



seriousfun
Novice

Jun 12, 2000, 4:07 AM

Post #1 of 2 (331 views)
Finding the most common value Can't Post

Could someone please help me find the string that occurs most often in an array. I have an array of string values that varies from 0 to 30, dependent on the search results and I wish to be able to find which value has been located the most.

All help is most appreciated.



japhy
Enthusiast

Jun 12, 2000, 6:16 AM

Post #2 of 2 (331 views)
Re: Finding the most common value [In reply to] Can't Post

If you can be sure that all the values in your array are numbers (and relatively small ones), then I suggest you use the following code:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


{
my @freq = ();
my $max = 0;
for (@orig) {
$freq[$_]++; # increment number of hits
$max = $freq[$_] if $freq[$_] > $max; # set new max value
}
@most_freq = grep $freq[$_] == $max, @freq;
}
</pre><HR></BLOCKQUOTE>

This populates the @most_freq array with the elements of the array @orig that have the most hits -- if two elements have the same number of hits, and that happens to be the max number of hits, then you might be interested in having BOTH of those elements.

If, instead, you might have strings instead of numbers, I'd use:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


{
my %freq = (); # hash instead of array
my $max = 0;
for (@orig) {
$freq{$_}++;
$max = $freq{$_} if $freq{$_} > $max;
}
@most_freq = grep $freq{$_} == $max, keys %freq;
}
</pre><HR></BLOCKQUOTE>

And, if you want to make this into some function so that, given a list of values, it returns: the max number of occurrences, a reference to a hash of element=>hits, and the list of elements with the most hits... then here's a starting block:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


($max, $freq_ref, @most_freq) = frequency(@list_of_values);

sub frequency {
my %freq = ();
my $max = 0;
my @most = ();
for (@_) {
$freq{$_}++;
$max = $freq{$_} if $max < $freq{$_};
}
@most = grep $freq{$_} == $max, keys %freq;
return ($max, \%freq, @most);
}
</pre><HR></BLOCKQUOTE>

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives