Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re^2: Count occurences of numbers

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


in reply to Re: Count occurences of numbers
in thread Count occurences of numbers

Hi,
++JavaFan - completely agreed. I should have pointed that out as well ;-), but this one time chose to not alter the OP's code too much...
Regards,
svenXY

Replies are listed 'Best First'.
Re^3: Count occurences of numbers
by walkingthecow (Friar) on Jan 20, 2009 at 15:15 UTC
    So, do you mean something like this:

    while (my $line = <>) {

    } ??
      Yes. That is, instead of all the code in the OP, you would want something like this:
      #!/usr/bin/perl use strict; my %idcount; while (<>) { if ( /,CO(\d+)\s/ ) { $idcount{$1}++ } } my ( $highest ) = sort { $idcount{$b} <=> $idcount{$a} } keys %idcount +; my $total = 0; $total += $_ for ( values %idcount ); print "Highest count was for group CO$highest, with $idcount{$highest} + out of $total users\n";
      For the sample data in the OP, that prints:
      Highest count was for group CO12345, with 4 out of 6 users
      (which I got by running the script in a terminal window, then pasting the 6 lines of data into the window, to emulate "typing" on stdin; the same result would happen by piping those six lines to the perl script from some other process, or storing them in a file and giving the file name as the sole command-line arg when running the script).

      UPDATED to include declaring, computing and printing "$total" (as per the OP spec).

      Oops... another update -- forgot about the case of possible ties for "highest". So, in place of the one line above that declares/assigns a value to $highest, you would need these two lines, which will set $highest to be a string of one or more comma-separated group-ids (including "CO" before the digits of non-initial id values):

      my ($maxcount) = sort { $idcount{$b} <=> $idcount{$a} } keys %idcount; my $highest = join(",CO", grep { $idcount{$_} == $maxcount } keys %idc +ount );
      Nothing else needs to change. Then replace "$idcount{$highest}" with "$maxcount" in the print statement.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2024-04-19 04:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found