in reply to Quick way to find the letter with the most occurences in a string

What have you tried? We generally appreciate a show-of-effort here - see How do I post a question effectively?.

There is no way to determine the most frequent letter without counting and comparing, and brevity of source code is generally not a good goal in and of itself (unless you are golfing).

That said, one way (TIMTOWTDI) to accomplish the counting with very little code is using inline Foreach Loops and split with a hash. You can then use sort with the numerical comparison operator (<=>) to find the key with the maximum value:

my $my_string="CCCAAAAACCCAAAAAAACCCCBBBCCAAACCBBACBBAAAAAAAAAAACAAAAA +AAAAA"; my %count; $count{$_}++ foreach split //, $my_string; print Dumper \%count; print my ($most_common) = sort {$count{$b} <=> $count{$a}} keys %count +;
  • Comment on Re: Quick way to find the letter with the most occurences in a string
  • Download Code

Replies are listed 'Best First'.
Re^2: Quick way to find the letter with the most occurences in a string
by choroba (Cardinal) on May 19, 2010 at 17:04 UTC
    Modified to handle cases with several characters with the maximal number of occurences:
    my %count; $count{$_}++ foreach split //,$string; my $max = (sort {$a<=>$b} values %count)[-1]; print $max,' ',grep $count{$_} == $max,keys %count;