Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Count occurences of numbers

by svenXY (Deacon)
on Jan 20, 2009 at 08:48 UTC ( [id://737513]=note: print w/replies, xml ) Need Help??


in reply to Count occurences of numbers

Hi,
I'd do it with a simple hash and no additional max-function, but here's a solution with your code. Basically, you need to count the number of groups and compare it with $max. Some other adjustments have been necessary, please see comments in the code:
#!/usr/bin/perl -w use strict; # always good unshift(@INC,"$ENV{'PWD'}"); use List::Util qw(max) ; # I could not find a "Util", but this one +seems fine ;-) my $file_name; my $ans; if (@ARGV == 1) { chomp ($file_name=$ARGV[0]); } else { print "\n\nPlease enter the file name to certify: "; chomp ($file_name=<STDIN>); while(1) { print "\n\nYou entered $file_name - is this correct? <y or n>:"; chomp ($ans=<STDIN>); if ($ans =~ /[Nn]/) { print "\n\nPlease enter the server name: "; chomp ($file_name=<STDIN>); next; } elsif ($ans =~ /[Yy]/) { last; } else { next; } } } open(STUFF,"<$file_name") or die "$!"; my %number_ids = () ; my $no_of_groups = 0; # used to count the number of groups of that +file while (my $line = <STUFF>) { $line =~ s/\s+\z// ; $line =~ s/\A\s+// ; my @csv = split(/:/, $line) ; if (defined($csv[1]) && ($csv[1] =~ m{((CO)\d{5})})) { my $num = $1; # my necessary due to strictures $number_ids{$num}++; $no_of_groups++; # increment Group Counter } elsif (defined($csv[0]) && ($csv[0] =~ m/^Group.*/i)) { show_most_popular(\%number_ids); print "$csv[1],"; %number_ids = (); } else { # what to do we do with peculiar lines? }; }; show_most_popular(\%number_ids); sub show_most_popular { my ($r_ids) = @_ ; return if !%$r_ids ; my $max = max(values %$r_ids) ; my @popular = () ; while (my ($id, $count) = each %$r_ids) { if ($count == $max) { push @popular, $id ; } ; } ; print join(',', sort @popular), " appeared most and $max out of $n +o_of_groups times\n"; # output as requested ;-) } ;

Regards,
svenXY

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://737513]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2024-04-16 14:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found