#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2005
    Posts
    5
    Rep Power
    0

    Find mode value in array


    Hey all,

    I'd like a quick and dirty way to find the mode value (i.e. the most frequently occurring value) in an array (my array is about 19,000 lines consisting of only numbers). Pretty much the easiest way possible would be nice, I'm no Perl guru myself.

    Thanks!

    ~ Scott
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2004
    Posts
    394
    Rep Power
    52
    Hi!

    Perl Code:
    my @array = (1,2,3,1,2,1,1,2,3,1,2,1,1,2,1,3);
    my %count;
    # we store the values and their frequency in a hash
    map{ $count{$_}++ } @array;
    # sort the hash by values
    for $k ( sort {$count{$a} <=> $count{$b}} keys %count ) {
        # the last one printed is the most frequent one
        print "$k => $count{$k}\n";
    }


    Regards, mawe
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    1
    Rep Power
    0
    I know this is an old thread, but it's ranking at the top of the search engines so I thought I would correct this script. While it's true that the last one printed is the most frequent one, there can be more than one mode. So I modified the script to sort the array in descending order and to print only those value(s) that are the mode:

    Perl Code:
    my @array = (1,2,3,1,2,1,1,2,3,1,2,1,1,2,1,3);
    my %count;
    my $top = 0;
    # we store the values and their frequency in a hash
    map{ $count{$_}++ } @array;
    # sort the hash in descending order by values so the modes appear first
    for $k ( sort {$count{$b} <=> $count{$a}} keys %count ) {
       # capture the count of the first element which is a mode
       $top = ($top == 0) ? $count{$k} : $top;
       # print only those elements with that count
        print "$k is a mode (appears $count{$k} times)\n" if $count{$k} == $top;
    }

IMN logo majestic logo threadwatch logo seochat tools logo