my @n; $n[$_{$_}] = $_ for map{$_{$_}++; $_} @list; print "Most frequent: $n[-1]";
sub most_frequent{ local *_=*_; $_[$_{$_}] = $_ for map{$_{$_}++; $_} +@_; $_[-1]; }
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?#!/usr/bin/perl use warnings; use strict; $|++; use Statistics::Frequency; use Benchmark qw( cmpthese ); my @data_small = qw( bob ); my @data_bigger = qw( bob bob bob tom sally jim bob bob bob tom sally +jim bob bob bob tom sally jim bob bob bob tom sally +jim bob bob bob tom sally jim bob bob bob tom sally +jim bob bob bob tom sally jim bob bob bob tom sally +jim bob bob bob tom sally jim bob bob bob tom sally +jim bob bob bob tom sally jim bob bob bob tom sally +jim bob bob bob tom sally jim bob bob bob tom sally +jim bob bob bob tom sally jim bob bob bob tom sally +jim ); cmpthese( 10_000, { mf_small => \&mf_small, sf_small => \&sf_small, } ); cmpthese( 2500, { mf_bigger => \&mf_bigger, sf_bigger => \&sf_bigger, } ); sub sf_small { my $f = Statistics::Frequency->new( @data_small ); my %f = reverse $f->frequencies; die "sf broken" unless $f{$f->frequencies_max} eq 'bob'; } sub sf_bigger { my $f = Statistics::Frequency->new( @data_bigger ); my %f = reverse $f->frequencies; die "sf broken" unless $f{$f->frequencies_max} eq 'bob'; } sub mf_small { my $f = most_frequent( @data_small ); die "mf broken" unless $f eq 'bob'; } sub mf_bigger { my $f = most_frequent( @data_bigger ); #die "mf broken" unless $f eq 'bob'; } sub most_frequent{ local *_=*_; $_[$_{$_}] = $_ for map{$_{$_}++; $_} @_; $_[-1]; } Benchmark: timing 10000 iterations of mf_small, sf_small... mf_small: 4 wallclock secs ( 2.56 usr + 0.54 sys = 3.10 CPU) @ 32 +25.81/s ( n=10000) sf_small: 1 wallclock secs ( 0.71 usr + 0.13 sys = 0.84 CPU) @ 11 +904.76/s ( n=10000) Rate mf_small sf_small mf_small 3226/s -- -73% sf_small 11905/s 269% -- Benchmark: timing 2500 iterations of mf_bigger, sf_bigger... mf_bigger: 23 wallclock secs (12.17 usr + 10.49 sys = 22.66 CPU) @ 1 +10.33/s (n= 2500) sf_bigger: 1 wallclock secs ( 1.11 usr + 0.14 sys = 1.25 CPU) @ 2 +000.00/s (n =2500) Rate mf_bigger sf_bigger mf_bigger 110/s -- -94% sf_bigger 2000/s 1713% --
In reply to Re: Re: •Re: Most frequent element in an array.
by dug
in thread Most frequent element in an array.
by BrowserUk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |